This repository contains some of my solutions to problems that were provided by leetcode.com.
-
1. Two Sum (solved here, tests)
Description
Given an array of integersnumsand an integertarget, return indices of the two numbers such that they add up totarget.You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
-
21. Merge Two Sorted Lists (solved here, tests)
Description
You are given the heads of two sorted linked listslist1andlist2.Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
-
104. Maximum Depth of Binary Tree (solved here, tests)
Description
Given therootof a binary tree, return its maximum depth.A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
-
125. Valid Palindrome (solved here, tests)
Description
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.Given a string
s, returntrueif it is a palindrome, orfalseotherwise. -
169. Majority Element (solved here, tests)
Description
Given an arraynumsof sizen, return the majority element.The majority element is the element that appears more than
[n / 2]times. You may assume that the majority element always exists in the array. -
191. Number of 1 Bits (solved here, tests)
Description
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). -
202. Happy Number (solved here, tests)
Description
Write an algorithm to determine if a numbernis happy.A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits.
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in
1are happy.Return
trueifnis a happy number, andfalseif not. -
217. Contains Duplicate (solved here, tests)
Description
Given an integer arraynums, returntrueif any value appears at least twice in the array, and returnfalseif every element is distinct. -
232. Implement Queue using Stacks (solved here, tests)
Description
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push,peek,pop, andempty).Implement the MyQueue class:
-
void push(int x)Pushes element x to the back of the queue. -
int pop()Removes the element from the front of the queue and returns it. -
int peek()Returns the element at the front of the queue. -
boolean empty()Returns true if the queue is empty, false otherwise.
Notes:
-
You must use only standard operations of a stack, which means only
push to top,peek/pop from top,size, andis emptyoperations are valid. -
Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
-
-
242. Valid Anagram (solved here, tests)
Description
Given two stringssandt, returntrueiftis an anagram ofs, andfalseotherwise.An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
-
283. Move Zeroes (solved here, tests)
Description
Given an integer arraynums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.Note that you must do this in-place without making a copy of the array.
-
303. Range Sum Query - Immutable (solved here, tests)
Description
Given an integer arraynums, handle multiple queries of the following type:- Calculate the sum of the elements of
numsbetween indicesleftandrightinclusive whereleft <= right.
Implement the NumArray class:
-
NumArray(int[] nums)Initializes the object with the integer arraynums. -
int sumRange(int left, int right)Returns the sum of the elements ofnumsbetween indicesleftandrightinclusive (i.e.nums[left] + nums[left + 1] + ... + nums[right]).
- Calculate the sum of the elements of
-
344. Reverse String (solved here, tests)
Description
Write a function that reverses a string. The input string is given as an array of characterss.You must do this by modifying the input array in-place with O(1) extra memory.
-
389. Find the Difference (solved here, tests)
Description
You are given two stringssandt.String
tis generated by random shuffling stringsand then add one more letter at a random position.Return the letter that was added to
t. -
404. Sum of Left Leaves (solved here, tests)
Description
Given therootof a binary tree, return the sum of all left leaves.A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.
-
496. Next Greater Element I (solved here, tests)
Description
The next greater element of some elementxin an array is the first greater element that is to the right ofxin the same array.You are given two distinct 0-indexed integer arrays
nums1andnums2, wherenums1is a subset ofnums2. For each0 <= i < nums1.length, find the indexjsuch thatnums1[i] == nums2[j]and determine the next greater element ofnums2[j]innums2. If there is no next greater element, then the answer for this query is-1.Return an array
ansof lengthnums1.lengthsuch thatans[i]is the next greater element as described above. -
566. Reshape the Matrix (solved here, tests)
Description
In MATLAB, there is a handy function called reshape which can reshape anm x nmatrix into a new one with a different sizer x ckeeping its original data.You are given an
m x nmatrixmatand two integersrandcrepresenting the number of rows and the number of columns of the wanted reshaped matrix.The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
-
589. N-ary Tree Preorder Traversal (solved here, tests)
Description
Given the root of an n-ary tree, return the preorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value. -
709. To Lower Case (solved here, tests)
Description
Given a strings, return the string after replacing every uppercase letter with the same lowercase letter. -
728. Self Dividing Numbers (solved here, tests)
Description
A self-dividing number is a number that is divisible by every digit it contains.- For example,
128is a self-dividing number because128 % 1 == 0,128 % 2 == 0, and128 % 8 == 0.
A self-dividing number is not allowed to contain the digit zero.
Given two integers
leftandright, return a list of all the self-dividing numbers in the range[left, right]. - For example,
-
771. Jewels and Stones (solved here, tests)
Description
You're given stringsjewelsrepresenting the types of stones that are jewels, andstonesrepresenting the stones you have. Each character instonesis a type of stone you have. You want to know how many of the stones you have are also jewels.Letters are case sensitive, so
"a"is considered a different type of stone from"A". -
804. Unique Morse Code Words (solved here, tests)
Description
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:'a'maps to".-",'b'maps to"-...",'c'maps to"-.-.", and so on.
For convenience, the full table for the
26letters of the English alphabet is given below:[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]Given an array of strings
wordswhere each word can be written as a concatenation of the Morse code of each letter.- For example,
"cab"can be written as"-.-..--...", which is the concatenation of"-.-.",".-", and"-...". We will call such a concatenation the transformation of a word.
Return the number of different transformations among all words we have.
-
832. Flipping an Image (solved here, tests)
Description
Given ann x nbinary matriximage, flip the image horizontally, then invert it, and return the resulting image.To flip an image horizontally means that each row of the image is reversed.
- For example, flipping
[1,1,0]horizontally results in[0,1,1].
To invert an image means that each
0is replaced by1, and each1is replaced by0.- For example, inverting
[0,1,1]results in[1,0,0].
- For example, flipping
-
876. Middle of the Linked List (solved here, tests)
Description
Given theheadof a singly linked list, return the middle node of the linked list.If there are two middle nodes, return the second middle node.
-
953. Verifying an Alien Dictionary (solved here, tests)
Description
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a differentorder. Theorderof the alphabet is some permutation of lowercase letters.Given a sequence of
wordswritten in the alien language, and theorderof the alphabet, returntrueif and only if the givenwordsare sorted lexicographically in this alien language. -
1021. Remove Outermost Parentheses (solved here, tests)
Description
A valid parentheses string is either empty"","(" + A + ")", orA + B, whereAandBare valid parentheses strings, and+represents string concatenation.For example,
"","()","(())()", and"(()(()))"are all valid parentheses strings.A valid parentheses string
sis primitive if it is nonempty, and there does not exist a way to split it intos = A + B, withAandBnonempty valid parentheses strings.Given a valid parentheses string
s, consider its primitive decomposition:s = P1 + P2 + ... + Pk, wherePiare primitive valid parentheses strings.Return
safter removing the outermost parentheses of every primitive string in the primitive decomposition ofs. -
1108. Defanging an IP Address (solved here, tests)
Description
Given a valid (IPv4) IP address, return a defanged version of that IP address.A defanged IP address replaces every period
"."with"[.]". -
1221. Split a String in Balanced Strings (solved here, tests)
Description
Balanced strings are those that have an equal quantity of'L'and'R'characters.Given a balanced string
s, split it in the maximum amount of balanced strings.Return the maximum amount of split balanced strings.
-
1232. Check If It Is a Straight Line (solved here, tests)
Description
You are given an arraycoordinates,coordinates[i] = [x, y], where[x, y]represents the coordinate of a point. Check if these points make a straight line in the XY plane. -
1281. Subtract the Product and Sum of Digits of an Integer (solved here, tests)
Description
Given an integer numbern, return the difference between the product of its digits and the sum of its digits. -
1290. Convert Binary Number in a Linked List to Integer (solved here, tests)
Description
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.Return the decimal value of the number in the linked list.
-
1313. Decompress Run-Length Encoded List (solved here, tests)
Description
We are given a list nums of integers representing a list compressed with run-length encoding.Consider each adjacent pair of elements
[freq, val] = [nums[2*i], nums[2*i+1]](withi >= 0). For each such pair, there arefreqelements with valuevalconcatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.Return the decompressed list.
-
1342. Number of Steps to Reduce a Number to Zero (solved here, tests)
Description
Given an integernum, return the number of steps to reduce it to zero.In one step, if the current number is even, you have to divide it by
2, otherwise, you have to subtract1from it. -
1356. Sort Integers by The Number of 1 Bits (solved here, tests)
Description
You are given an integer arrayarr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order. Return the array after sorting it. -
1365. How Many Numbers Are Smaller Than the Current Number (solved here, tests)
Description
Given the arraynums, for eachnums[i]find out how many numbers in the array are smaller than it. That is, for eachnums[i]you have to count the number of valid j's such thatj != iandnums[j] < nums[i].Return the answer in an array.
-
1389. Create Target Array in the Given Order (solved here, tests)
Description
Given two arrays of integersnumsandindex. Your task is to create target array under the following rules:-Initially target array is empty.
-From left to right read
nums[i]andindex[i], insert at indexindex[i]the valuenums[i]in target array.-Repeat the previous step until there are no elements to read in
numsandindex.-Return the target array.
It is guaranteed that the insertion operations will be valid.
-
1431. Kids With the Greatest Number of Candies (solved here, tests)
Description
There arenkids with candies. You are given an integer arraycandies, where eachcandies[i]represents the number of candies thei-thkid has, and an integerextraCandies, denoting the number of extra candies that you have.Return a boolean array
resultof lengthn, whereresult[i]istrueif, after giving thei-thkid all theextraCandies, they will have the greatest number of candies among all the kids, orfalseotherwise.Note that multiple kids can have the greatest number of candies.
-
1436. Destination City (solved here, tests)
Description
You are given the arraypaths, wherepaths[i] = [cityAi, cityBi]means there exists a direct path going fromcityAitocityBi. Return the destination city, that is, the city without any path outgoing to another city.It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.
-
1470. Shuffle the Array (solved here, tests)
Description
Given the arraynumsconsisting of2nelements in the form[x1,x2,...,xn,y1,y2,...,yn].Return the array in the form
[x1,y1,x2,y2,...,xn,yn]. -
1480. Running Sum of 1d Array (solved here, tests)
Description
Given an arraynums. We define a running sum of an array asrunningSum[i] = sum(nums[0]…nums[i]).Return the running sum of
nums. -
1486. XOR Operation in an Array (solved here, tests)
Description
You are given an integernand an integerstart.Define an array nums where
nums[i] = start + 2 * i(0-indexed) andn == nums.length.Return the bitwise XOR of all elements of
nums. -
1502. Can Make Arithmetic Progression From Sequence (solved here, tests)
Description
A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.Given an array of numbers
arr, returntrueif the array can be rearranged to form an arithmetic progression. Otherwise, returnfalse. -
1512. Number of Good Pairs (solved here, tests)
Description
Given an array of integersnums, return the number of good pairs.A pair
(i, j)is called good ifnums[i] == nums[j]andi < j. -
1528. Shuffle String (solved here, tests)
Description
You are given a stringsand an integer arrayindicesof the same length. The stringswill be shuffled such that the character at thei-thposition moves toindices[i]in the shuffled string.Return the shuffled string.
-
1534. Count Good Triplets (solved here, tests)
Description
Given an array of integersarr, and three integersa,bandc. You need to find the number of good triplets.A triplet
(arr[i], arr[j], arr[k])is good if the following conditions are true:-
0 <= i < j < k < arr.length -
|arr[i] - arr[j]| <= a -
|arr[j] - arr[k]| <= b -
|arr[i] - arr[k]| <= c
Where
|x|denotes the absolute value ofx.Return the number of good triplets.
-
-
1572. Matrix Diagonal Sum (solved here, tests)
Description
Given a square matrixmat, return the sum of the matrix diagonals.Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
-
1588. Sum of All Odd Length Subarrays (solved here, tests)
Description
Given an array of positive integersarr, calculate the sum of all possible odd-length subarrays.A subarray is a contiguous subsequence of the array.
Return the sum of all odd-length subarrays of
arr. -
1603. Design Parking System (solved here, tests)
Description
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.Implement the
ParkingSystemclass:ParkingSystem(int big, int medium, int small)Initializes object of theParkingSystemclass. The number of slots for each parking space are given as part of the constructor.bool addCar(int carType)Checks whether there is a parking space ofcarTypefor the car that wants to get into the parking lot.carTypecan be of three kinds: big, medium, or small, which are represented by1,2, and3respectively. A car can only park in a parking space of itscarType. If there is no space available, returnfalse, else park the car in that size space and returntrue.
-
1614. Maximum Nesting Depth of the Parentheses (solved here, tests)
Description
A string is a valid parentheses string (denoted VPS) if it meets one of the following:-
It is an empty string
"", or a single character not equal to"("or")", -
It can be written as
AB(Aconcatenated withB), whereAandBare VPS's, or -
It can be written as
(A), whereAis a VPS.
We can similarly define the nesting depth
depth(S)of any VPSSas follows:-
depth("") = 0 -
depth(C) = 0, whereCis a string with a single character not equal to"("or")". -
depth(A + B) = max(depth(A), depth(B)), whereAandBare VPS's. -
depth("(" + A + ")") = 1 + depth(A), whereAis a VPS.
For example,
"","()()", and"()(()())"are VPS's (with nesting depths 0, 1, and 2), and")("and"(()"are not VPS's.Given a VPS represented as string
s, return the nesting depth ofs. -
-
1656. Design an Ordered Stream (solved here, tests)
Description
There is a stream ofn(idKey, value)pairs arriving in an arbitrary order, whereidKeyis an integer between1andnandvalueis a string. No two pairs have the same id.Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values.
Implement the
OrderedStreamclass:OrderedStream(int n)Constructs the stream to takenvalues.String[] insert(int idKey, String value)Inserts the pair(idKey, value)into the stream, then returns the largest possible chunk of currently inserted values that appear next in the order.
-
1662. Check If Two String Arrays are Equivalent (solved here, tests)
Description
Given two string arraysword1andword2, returntrueif the two arrays represent the same string, andfalseotherwise.A string is represented by an array if the array elements concatenated in order forms the string.
-
1684. Count the Number of Consistent Strings (solved here, tests)
Description
You are given a stringallowedconsisting of distinct characters and an array of stringswords. A string is consistent if all characters in the string appear in the stringallowed.Return the number of consistent strings in the array
words. -
1688. Count of Matches in Tournament (solved here, tests)
Description
You are given an integern, the number of teams in a tournament that has strange rules:If the current number of teams is even, each team gets paired with another team. A total of
n / 2matches are played, andn / 2teams advance to the next round.If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of
(n - 1) / 2matches are played, and(n - 1) / 2 + 1teams advance to the next round.Return the number of matches played in the tournament until a winner is decided.
-
1704. Determine if String Halves Are Alike (solved here, tests)
Description
You are given a stringsof even length. Split this string into two halves of equal lengths, and letabe the first half andbbe the second half.Two strings are alike if they have the same number of vowels
('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice thatscontains uppercase and lowercase letters.Return
trueifaandbare alike. Otherwise, returnfalse. -
1720. Decode XORed Array (solved here, tests)
Description
There is a hidden integer arrayarrthat consists ofnnon-negative integers.It was encoded into another integer array
encodedof lengthn - 1, such thatencoded[i] = arr[i] XOR arr[i + 1]. For example, ifarr = [1,0,2,1], thenencoded = [1,2,3].You are given the
encodedarray. You are also given an integerfirst, that is the first element ofarr, i.e.arr[0].Return the original array
arr. It can be proved that the answer exists and is unique. -
1773. Count Items Matching a Rule (solved here, tests)
Description
You are given an arrayitems, where eachitems[i] = [type-i, color-i, name-i]describes the type, color, and name of thei-thitem. You are also given a rule represented by two strings,ruleKeyandruleValue.The
i-thitem is said to match the rule if one of the following is true:ruleKey == "type"andruleValue == type-i.ruleKey == "color"andruleValue == color-i.ruleKey == "name"andruleValue == name-i.Return the number of items that match the given rule.
-
1779. Find Nearest Point That Has the Same X or Y Coordinate (solved here, tests)
Description
You are given two integers,xandy, which represent your current location on a Cartesian grid:(x, y). You are also given an arraypointswhere eachpoints[i] = [ai, bi]represents that a point exists at(ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return
-1.The Manhattan distance between two points
(x1, y1)and(x2, y2)isabs(x1 - x2) + abs(y1 - y2). -
1790. Check if One String Swap Can Make Strings Equal (solved here, tests)
Description
You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false. -
1791. Find Center of Star Graph (solved here, tests)
Description
There is an undirected star graph consisting ofnnodes labeled from1ton. A star graph is a graph where there is one center node and exactlyn - 1edges that connect the center node with every other node.You are given a 2D integer array
edgeswhere eachedges[i] = [ui, vi]indicates that there is an edge between the nodesuiandvi. Return the center of the given star graph. -
1816. Truncate Sentence (solved here, tests)
Description
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).- For example, "Hello World", "HELLO", and "hello world hello world" are all sentences.
You are given a sentence
sand an integerk. You want to truncatessuch that it contains only the firstkwords. Returnsafter truncating it. -
1832. Check if the Sentence Is Pangram (solved here, tests)
Description
A pangram is a sentence where every letter of the English alphabet appears at least once.Given a string
sentencecontaining only lowercase English letters, returntrueifsentenceis a pangram, orfalseotherwise. -
1844. Replace All Digits with Characters (solved here, tests)
Description
You are given a 0-indexed stringsthat has lowercase English letters in its even indices and digits in its odd indices.There is a function
shift(c, x), wherecis a character andxis a digit, that returns thex-thcharacter afterc.- For example,
shift('a', 5) = 'f'andshift('x', 0) = 'x'.
For every odd index
i, you want to replace the digits[i]withshift(s[i-1], s[i]).Return
safter replacing all digits. It is guaranteed thatshift(s[i-1], s[i])will never exceed'z'. - For example,
-
1859. Sorting the Sentence (solved here, tests)
Description
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.
For example, the sentence
"This is a sentence"can be shuffled as"sentence4 a3 is2 This1"or"is2 sentence4 This1 a3". Given a shuffled sentencescontaining no more than9words, reconstruct and return the original sentence. -
1913. Maximum Product Difference Between Two Pairs (solved here, tests)
Description
The product difference between two pairs(a, b)and(c, d)is defined as(a * b) - (c * d).- For example, the product difference between
(5, 6)and(2, 7)is(5 * 6) - (2 * 7) = 16.
Given an integer array
nums, choose four distinct indicesw,x,y, andzsuch that the product difference between pairs(nums[w], nums[x])and(nums[y], nums[z])is maximized.Return the maximum such product difference.
- For example, the product difference between
-
1920. Build Array from Permutation (solved here, tests)
Description
Given a zero-based permutation nums (0-indexed), build an arrayansof the same length whereans[i] = nums[nums[i]]for each0 <= i < nums.lengthand return it.A zero-based permutation nums is an array of distinct integers from
0tonums.length - 1(inclusive). -
1929. Concatenation of Array (solved here, tests)
Description
Given an integer arraynumsof lengthn, you want to create an arrayansof length2nwhereans[i] == nums[i]andans[i + n] == nums[i]for0 <= i < n(0-indexed).Specifically,
ansis the concatenation of twonumsarrays.Return the array
ans. -
1967. Number of Strings That Appear as Substrings in Word (solved here, tests)
Description
Given an array of stringspatternsand a stringword, return the number of strings inpatternsthat exist as a substring inword.A substring is a contiguous sequence of characters within a string.
-
2006. Count Number of Pairs With Absolute Difference K (solved here, tests)
Description
Given an integer arraynumsand an integerk, return the number of pairs(i, j)wherei < jsuch that|nums[i] - nums[j]| == k.The value of |x| is defined as:
xifx >= 0.-xifx < 0. -
2011. Final Value of Variable After Performing Operations (solved here, tests)
Description
There is a programming language with only four operations and one variableX:-
++XandX++increments the value of the variableXby1. -
--XandX--decrements the value of the variableXby1.
Initially, the value of
Xis0.Given an array of strings operations containing a list of operations, return the final value of
Xafter performing all the operations. -
-
2037. Minimum Number of Moves to Seat Everyone (solved here, tests)
Description
There arenseats andnstudents in a room. You are given an arrayseatsof lengthn, whereseats[i]is the position of thei-thseat. You are also given the arraystudentsof lengthn, wherestudents[j]is the position of thej-thstudent.You may perform the following move any number of times:
Increase or decrease the position of the
i-thstudent by1(i.e., moving thei-thstudent from positionxtox + 1orx - 1) Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat.Note that there may be multiple seats or students in the same position at the beginning.
-
2103. Rings and Rods (solved here, tests)
Description
There arenrings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from0to9.You are given a string
ringsof length2nthat describes thenrings that are placed onto the rods. Every two characters inringsforms a color-position pair that is used to describe each ring where:-
The first character of the
i-thpair denotes thei-thring's color ('R','G','B'). -
The second character of the
i-thpair denotes the rod that thei-thring is placed on ('0'to'9').
For example,
"R3G2B1"describesn == 3rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.Return the number of rods that have all three colors of rings on them.
-
-
2114. Maximum Number of Words Found in Sentences (solved here, tests)
Description
A sentence is a list of words that are separated by a single space with no leading or trailing spaces.You are given an array of strings
sentences, where eachsentences[i]represents a single sentence.Return the maximum number of words that appear in a single sentence.
-
2160. Minimum Sum of Four Digit Number After Splitting Digits (solved here, tests)
Description
You are given a positive integernumconsisting of exactly four digits. Splitnuminto two new integersnew1andnew2by using the digits found innum. Leading zeros are allowed innew1andnew2, and all the digits found innummust be used.For example, given
num = 2932, you have the following digits: two2's, one9and one3. Some of the possible pairs[new1, new2]are[22, 93],[23, 92],[223, 9]and[2, 329].Return the minimum possible sum of
new1andnew2. -
2176. Count Equal and Divisible Pairs in an Array (solved here, tests)
Description
Given a 0-indexed integer arraynumsof lengthnand an integerk, return the number of pairs(i, j)where0 <= i < j < n, such thatnums[i] == nums[j]and(i * j)is divisible byk. -
2185. Counting Words With a Given Prefix (solved here, tests)
Description
You are given an array of stringswordsand a stringpref.Return the number of strings in
wordsthat containprefas a prefix.A prefix of a string
sis any leading contiguous substring ofs. -
2194. Cells in a Range on an Excel Sheet (solved here, tests)
Description
A cell(r, c)of an excel sheet is represented as a string"<col><row>"where:-
<col>denotes the column numbercof the cell. It is represented by alphabetical letters.For example, the
1stcolumn is denoted by'A', the2ndby'B', the3rdby'C', and so on.-
<row>is the row numberrof the cell. Ther-throw is represented by the integerr.You are given a string
sin the format"<col1><row1>:<col2><row2>", where<col1>represents the columnc1,<row1>represents the rowr1,<col2>represents the column c2, and represents the rowr2, such thatr1 <= r2andc1 <= c2.Return the list of cells
(x, y)such thatr1 <= x <= r2andc1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows. -
2235. Add Two Integers (solved here, tests)
Description
Given two integersnum1andnum2, return the sum of the two integers. -
2236. Root Equals Sum of Children (solved here, tests)
Description
You are given therootof a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child.Return
trueif the value of the root is equal to the sum of the values of its two children, orfalseotherwise.
-
2. Add Two Numbers (solved here, tests)
Description
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return thesumas a linked list.You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: l1 = [2,4,3], l2 = [5,6,4]Output: [7,0,8]Explanation: 342 + 465 = 807 -
8. String to Integer (atoi) (solved here, tests)
Description
Implement themyAtoi(string s)function, which converts a string to a 32-bit signed integer (similar to C/C++'satoifunction).The algorithm for
myAtoi(string s)is as follows:- Read in and ignore any leading whitespace.
- Check if the next character (if not already at the end of the string) is
'-'or'+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. - Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
- Convert these digits into an integer (i.e.
"123" -> 123,"0032" -> 32). If no digits were read, then the integer is0. Change the sign as necessary (from step 2). - If the integer is out of the 32-bit signed integer range
[-2^31, 2^31 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than-2^31should be clamped to-2^31, and integers greater than2^31 - 1should be clamped to2^31 - 1. - Return the integer as the final result.
Note:
Only the space character
' 'is considered a whitespace character. Do not ignore any characters other than the leading whitespace or the rest of the string after the digits. -
29. Divide Two Integers (solved here, tests)
Description
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.The integer division should truncate toward zero, which means losing its fractional part. For example,
8.345would be truncated to8, and-2.7335would be truncated to-2.Return the quotient after dividing dividend by divisor.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range:
[−2^31, 2^31 − 1]. For this problem, if the quotient is strictly greater than2^31 - 1, then return2^31 - 1, and if the quotient is strictly less than-2^31, then return-2^31. -
38. Count and Say (solved here, tests)
Description
The count-and-say sequence is a sequence of digit strings defined by the recursive formula:countAndSay(1) = "1"countAndSay(n)is the way you would "say" the digit string fromcountAndSay(n-1), which is then converted into a different digit string. To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.For example, the saying and conversion for digit string
"3322251":Given a positive integer
n, return then-thterm of the count-and-say sequence. -
535. Encode and Decode TinyURL (solved here, tests)
Description
TinyURL is a URL shortening service where you enter a URL such ashttps://leetcode.com/problems/design-tinyurland it returns a short URL such ashttp://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL.There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
Implement the
Solutionclass:-
Solution()Initializes the object of the system. -
String encode(String longUrl)Returns a tiny URL for the givenlongUrl. -
String decode(String shortUrl)Returns the original long URL for the givenshortUrl. It is guaranteed that the givenshortUrlwas encoded by the same object.
-
-
1282. Group the People Given the Group Size They Belong To (solved here, tests)
Description
There arenpeople that are split into some unknown number of groups. Each person is labeled with a unique ID from0ton - 1.You are given an integer array
groupSizes, wheregroupSizes[i]is the size of the group that personiis in. For example, ifgroupSizes[1] = 3, then person1must be in a group of size3.Return a list of groups such that each person
iis in a group of sizegroupSizes[i].Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.
-
1329. Sort the Matrix Diagonally (solved here, tests)
Description
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting frommat[2][0], wherematis a6 x 3matrix, includes cellsmat[2][0],mat[3][1], andmat[4][2].Given an
m x nmatrixmatof integers, sort each matrix diagonal in ascending order and return the resulting matrix. -
1409. Queries on a Permutation With Key (solved here, tests)
Description
Given the arrayqueriesof positive integers between1andm, you have to process allqueries[i](fromi=0toi=queries.length-1) according to the following rules:-
In the beginning, you have the permutation
P=[1,2,3,...,m]. -
For the current
i, find the position ofqueries[i]in the permutationP(indexing from 0) and then move this at the beginning of the permutationP. Notice that the position ofqueries[i]inPis the result forqueries[i].
Return an array containing the result for the given
queries. -
-
1476. Subrectangle Queries (solved here, tests)
Description
Implement the classSubrectangleQuerieswhich receives arows x colsrectangle as a matrix of integers in the constructor and supports two methods:updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)
Updates all values with
newValuein the subrectangle whose upper left coordinate is(row1,col1)and bottom right coordinate is(row2,col2).getValue(int row, int col)
Returns the current value of the coordinate
(row,col)from the rectangle. -
1769. Minimum Number of Operations to Move All Balls to Each Box (solved here, tests)
Description
You have n boxes. You are given a binary stringboxesof lengthn, whereboxes[i]is'0'if thei-thbox is empty, and'1'if it contains one ball.In one operation, you can move one ball from a box to an adjacent box. Box
iis adjacent to boxjifabs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.Return an array
answerof sizen, whereanswer[i]is the minimum number of operations needed to move all the balls to thei-thbox.Each
answer[i]is calculated considering the initial state of the boxes. -
1828. Queries on Number of Points Inside a Circle (solved here, tests)
Description
You are given an arraypointswherepoints[i] = [xi, yi]is the coordinates of thei-thpoint on a 2D plane. Multiple points can have the same coordinates.You are also given an array
querieswherequeries[j] = [xj, yj, rj]describes a circle centered at(xj, yj)with a radius ofrj.For each query
queries[j], compute the number of points inside thej-thcircle. Points on the border of the circle are considered inside.Return an array
answer, whereanswer[j]is the answer to thej-thquery. -
2079. Watering Plants (solved here, tests)
Description
You want to waternplants in your garden with a watering can. The plants are arranged in a row and are labeled from0ton - 1from left to right where thei-thplant is located atx = i. There is a river atx = -1that you can refill your watering can at.Each plant needs a specific amount of water. You will water the plants in the following way:
-
Water the plants in order from left to right.
-
After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can.
-
You cannot refill the watering can early.
You are initially at the river (i.e.,
x = -1). It takes one step to move one unit on the x-axis.Given a 0-indexed integer array
plantsofnintegers, whereplants[i]is the amount of water thei-thplant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants. -
-
2120. Execution of All Suffix Instructions Staying in a Grid (solved here, tests)
Description
There is ann x ngrid, with the top-left cell at(0, 0)and the bottom-right cell at(n - 1, n - 1). You are given the integernand an integer arraystartPoswherestartPos = [startrow, startcol]indicates that a robot is initially at cell(startrow, startcol).You are also given a 0-indexed string
sof lengthmwheres[i]is thei-thinstruction for the robot:'L'(move left),'R'(move right),'U'(move up), and'D'(move down).The robot can begin executing from any
i-thinstruction ins. It executes the instructions one by one towards the end ofsbut it stops if either of these conditions is met:- The next instruction will move the robot off the grid.
- There are no more instructions left to execute.
Return an array
answerof lengthmwhereanswer[i]is the number of instructions the robot can execute if the robot begins executing from thei-thinstruction ins. -
2125. Number of Laser Beams in a Bank (solved here, tests)
Description
Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string arraybankrepresenting the floor plan of the bank, which is anm x n2D matrix.bank[i]represents thei-throw, consisting of'0's and'1's.'0'means the cell is empty, while'1'means the cell has a security device.There is one laser beam between any two security devices if both conditions are met:
-
The two devices are located on two different rows:
r1andr2, wherer1 < r2. -
For each row
iwherer1 < i < r2, there are no security devices in thei-throw.
Laser beams are independent, i.e., one beam does not interfere nor join with another.
Return the total number of laser beams in the bank.
-
-
2149. Rearrange Array Elements by Sign (solved here, tests)
Description
You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.You should rearrange the elements of nums such that the modified array follows the given conditions:
Every consecutive pair of integers have opposite signs. For all integers with the same sign, the order in which they were present in nums is preserved. The rearranged array begins with a positive integer. Return the modified array after rearranging the elements to satisfy the aforementioned conditions.
-
2161. Partition Array According to Given Pivot (solved here, tests)
Description
You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:- Every element less than
pivotappears before every element greater thanpivot. - Every element equal to
pivotappears in between the elements less than and greater thanpivot. The relative order of the elements less thanpivotand the elements greater thanpivotis maintained. More formally, consider everypi,pjwherepiis the new position of thei-thelement andpjis the new position of thej-thelement. For elements less than pivot, ifi < jandnums[i] < pivotandnums[j] < pivot, thenpi < pj. Similarly for elements greater than pivot, ifi < jandnums[i] > pivotandnums[j] > pivot, thenpi < pj. Returnnumsafter the rearrangement.
- Every element less than
-
4. Median of Two Sorted Arrays (solved here, tests)
Description
Given two sorted arraysnums1andnums2of sizemandnrespectively, return the median of the two sorted arrays.The overall run time complexity should be
O(log (m+n)).
