Year
2023 archive
A year-sized slice of the daily archive, ordered newest first.
363 entries
363 entries from 2023.
31.12.2023
easy1624. Largest Substring Between Two Equal Characters
Max distance between same chars in string.
30.12.2023
easy1897. Redistribute Characters to Make All Strings Equal
Is it possible to split all the words[] characters into words.size groups.
29.12.2023
hard1335. Minimum Difficulty of a Job Schedule
Min sum of maximums jobDifficulty[i] per day d preserving the order
28.12.2023
hard1531. String Compression II
Min length of run-length encoded aabcc -> a2bc3 after deleting at most k characters
27.12.2023
medium1578. Minimum Time to Make Rope Colorful
Min sum of removed duplicates in array.
26.12.2023
medium1155. Number of Dice Rolls With Target Sum
Ways to throw once n dices with k faces to make target sum.
25.12.2023
medium91. Decode Ways
Ways to decode back 'A' -> '1', 'B' -> '2' … 'Z' -> '26'
24.12.2023
easy1758. Minimum Changes To Make Alternating Binary String
In a stressfull situation better to just use 4 counters: oddOnes, evenOnes, oddZeros, evenZeros. Then do something with them.
23.12.2023
easy1496. Path Crossing
Is path string of 'N', 'E', 'W', 'S' crosses
22.12.2023
easy1422. Maximum Score After Splitting a String
Max left zeros + right ones in 01-array
21.12.2023
easy1637. Widest Vertical Area Between Two Points Containing No Points
Max x window between xy points
20.12.2023
easy2706. Buy Two Chocolates
Money change after two chocolates bought
19.12.2023
easy661. Image Smoother
x3 average of each cell in 2D matrix
18.12.2023
easy1913. Maximum Product Difference Between Two Pairs
max second max - min second min
17.12.2023
medium2353. Design a Food Rating System
Given foods, cuisines and ratings implement efficient methods changeRating(food, newRating) and highestRated(cuisine)
16.12.2023
easy242. Valid Anagram
#### Join me on Telegram
15.12.2023
easy1436. Destination City
#### Join me on Telegram
14.12.2023
easy2482. Difference Between Ones and Zeros in Row and Column
diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj
13.12.2023
easy1582. Special Positions in a Binary Matrix
#### Join me on Telegram
12.12.2023
easy1464. Maximum Product of Two Elements in an Array
#### Join me on Telegram
11.12.2023
easy1287. Element Appearing More Than 25% In Sorted Array
Most frequent element
10.12.2023
easy867. Transpose Matrix
Transpose 2D matrix
09.12.2023
easy94. Binary Tree Inorder Traversal
Inorder traversal
08.12.2023
easy606. Construct String from Binary Tree
Pre-order binary tree serialization
07.12.2023
easy1903. Largest Odd Number in String
Largest odd number in a string
05.12.2023
easy1688. Count of Matches in Tournament
Count of odd-even matches according to the rules x/2 or 1+(x-1)/2.
04.12.2023
easy2264. Largest 3-Same-Digit Number in String
Largest 3-same-digit number in a string
03.12.2023
easy1266. Minimum Time Visiting All Points
Path coordinates distance in XY plane
02.12.2023
easy1160. Find Words That Can Be Formed by Characters
Sum of words lengths constructed by chairs
01.12.2023
easy1662. Check If Two String Arrays are Equivalent
Two dimensional array equals
30.11.2023
hard1611. Minimum One Bit Operations to Make Integers Zero
Minimum rounds of inverting rightmost bit or left of the rightmost 1 bit to make n zero
29.11.2023
easy191. Number of 1 Bits
Bits count
28.11.2023
hard2147. Number of Ways to Divide a Long Corridor
Count ways to place borders separating pairs of 'S' in 'SP' string
27.11.2023
medium935. Knight Dialer
Count of dialer n-length numbers formed by pressing in a chess Knight's moves
26.11.2023
medium1727. Largest Submatrix With Rearrangements
Max area of 1 submatrix after sorting columns optimally
25.11.2023
medium1685. Sum of Absolute Differences in a Sorted Array
Array to sum j(abs(arr[i] - arr[j])) for each i
24.11.2023
medium1561. Maximum Number of Coins You Can Get
Get sum of second maxes of triples from array
23.11.2023
medium1630. Arithmetic Subarrays
Query array ranges can form arithmetic sequence
22.11.2023
medium1424. Diagonal Traverse II
Diagonal 2D matrix order with prunes
21.11.2023
medium1814. Count Nice Pairs in an Array
Count pairs x-rev(x) == y-rev(y), where rev(123) = 321
20.11.2023
medium2391. Minimum Amount of Time to Collect Garbage
Time to pick 3-typed garbage[] by 3 trucks traveling to the right travel[] time
19.11.2023
medium1887. Reduction Operations to Make the Array Elements Equal
Number of operations to decrease all elements to the next smallest
18.11.2023
medium1838. Frequency of the Most Frequent Element
Max count of equal numbers if increment arr[i] k times
17.11.2023
medium1877. Minimize Maximum Pair Sum in Array
Minimum possible max of array pairs sums
16.11.2023
medium1980. Find Unique Binary String
First absent number in a binary string array
15.11.2023
medium1846. Maximum Element After Decreasing and Rearranging
Max number from converting array to non decreasing
14.11.2023
medium1930. Unique Length-3 Palindromic Subsequences
Count of unique palindrome substrings of length 3
13.11.2023
medium2785. Sort Vowels in a String
Sort vowels in a string
12.11.2023
hard815. Bus Routes
Minimum buses to travel by given routes
11.11.2023
hard2642. Design Graph With Shortest Path Calculator
Implement graph with shortest path searching
10.11.2023
medium1743. Restore the Array From Adjacent Pairs
Restore an array from adjacent pairs
09.11.2023
medium1759. Count Number of Homogenous Substrings
Count of substrings of same chars
08.11.2023
medium2849. Determine if a Cell Is Reachable at a Given Time
Is path possible on grid sx, sy -> fx, fy
07.11.2023
medium1921. Eliminate Maximum Number of Monsters
Count possible 1-minute kills in a game of dist[] targets falling with speed[]
06.11.2023
medium1845. Seat Reservation Manager
Design reservation number system
05.11.2023
medium1535. Find the Winner of an Array Game
Find maximum of the k nearest in array
04.11.2023
medium1503. Last Moment Before All Ants Fall Out of a Plank
Max time ants on a line when goint left and right
03.11.2023
medium767. Reorganize String
Non-repeating consequent chars string from another string
02.11.2023
medium2265. Count Nodes Equal to Average of Subtree
Number of nodes in a tree where val == sum / count of a subtree
01.11.2023
easy501. Find Mode in Binary Search Tree
Most frequent elements in a Binary Search Tree
31.10.2023
medium2433. Find The Original Array of Prefix Xor
Reverse xor operation
30.10.2023
easy1356. Sort Integers by The Number of 1 Bits
Sort an array comparing by bit count and value
29.10.2023
hard458. Poor Pigs
Minimum pigs to find a poison in buckets in k rounds
28.10.2023
hard1220. Count Vowels Permutation
Count of n lengths paths according to graph rules a->e, e->(a, i), etc
27.10.2023
medium5. Longest Palindromic Substring
Longest palindrome substring
26.10.2023
medium823. Binary Trees With Factors
Number of trees from arr where each k node has i and j leafs arr[k]=arr[j] arr[i]
25.10.2023
medium779. K-th Symbol in Grammar
Binary Tree 0 -> 01, 1 -> 10 at [n][k] position
24.10.2023
medium515. Find Largest Value in Each Tree Row
Binary Tree's maxes of the levels
23.10.2023
easy342. Power of Four
Is n == x^4?
22.10.2023
hard1793. Maximum Score of a Good Subarray
Max of window min (window size) for window having nums[k]
21.10.2023
hard1425. Constrained Subsequence Sum
Max sum of subsequence i - j <= k
20.10.2023
medium341. Flatten Nested List Iterator
Implement graph iterator
19.10.2023
medium844. Backspace String Compare
Remove all of the backspaced chars before comparing
18.10.2023
hard2050. Parallel Courses III
Shortest time to visit all nodes in relations=[from, to] graph
17.10.2023
medium1361. Validate Binary Tree Nodes
Is Binary Tree of leftChild[] & rightChild[] valid
16.10.2023
easy119. Pascal's Triangle II
Pascal's Triangle
15.10.2023
hard1269. Number of Ways to Stay in the Same Place After Some Steps
Number of ways to return to 0 after moving left, right or stay steps time
14.10.2023
hard2742. Painting the Walls
Min cost to complete all tasks using one paid cost[] & time[] and one free 0 & 1 workers
13.10.2023
easy746. Min Cost Climbing Stairs
Classic DP: climbing stairs
12.10.2023
hard1095. Find in Mountain Array
Binary Search in a mountain
11.10.2023
hard2251. Number of Flowers in Full Bloom
Array of counts of segments in intersection
10.10.2023
hard2009. Minimum Number of Operations to Make Array Continuous
Min replacements to make array continuous a[i] = a[i - 1] + 1
9.10.2023
medium34. Find First and Last Position of Element in Sorted Array
Binary Search range
8.10.2023
hard1458. Max Dot Product of Two Subsequences
Max product of two subsequences
7.10.2023
hard1420. Build Array Where You Can Find The Maximum Exactly K Comparisons
Count possible arrays of n 1..m values increasing k times
6.10.2023
medium343. Integer Break
Max multiplication of the number split
5.10.2023
medium229. Majority Element II
Elements with frequency > size / 3
4.10.2023
easy706. Design HashMap
Design a HashMap
3.10.2023
easy1512. Number of Good Pairs
Count equal pairs
2.10.2023
medium2038. Remove Colored Pieces if Both Neighbors are the Same Color
Is A wins in middle-removing AAA or BBB game
1.10.2023
easy557. Reverse Words in a String III
Reverse words
30.09.2023
medium456. 132 Pattern
132 pattern in array
29.09.2023
easy896. Monotonic Array
Is array monotonic
28.09.2023
easy905. Sort Array By Parity
Sort an array by even-odd
27.09.2023
medium880. Decoded String at Index
k-th character in an encoded string like a3b2=aaabaaab
26.09.2023
medium316. Remove Duplicate Letters
Lexicographical smallest subsequence without duplicates
25.09.2023
easy389. Find the Difference
Strings difference by a single char
24.09.2023
medium799. Champagne Tower
Positional flow value in a Pascal's Triangle
23.09.2023
medium1048. Longest String Chain
Longest chain of words with single character added
22.09.2023
easy392. Is Subsequence
Is string a subsequence of another
21.09.2023
hard4. Median of Two Sorted Arrays
Median in two concatenated sorted arrays
20.09.2023
medium1658. Minimum Operations to Reduce X to Zero
Min suffix-prefix to make an x
19.09.2023
medium287. Find the Duplicate Number
Found duplicate in array, each value is in 1..
18.09.2023
easy1337. The K Weakest Rows in a Matrix
k indices with smallest row sum in a binary matrix
16.09.2023
medium1631. Path With Minimum Effort
Minimum absolute difference in path top-left to right-bottom
15.09.2023
medium1584. Min Cost to Connect All Points
Min manhatten distance connected graph
14.09.2023
hard332. Reconstruct Itinerary
Smallest lexical order path using all the tickets
13.09.2023
hard135. Candy
Minimum candies count to satisfy condition: ratings[i] < ratings[i-1] must give more candies to i-1
12.09.2023
medium1647. Minimum Deletions to Make Character Frequencies Unique
Minimum removes duplicate frequency chars from string
11.09.2023
medium1282. Group the People Given the Group Size They Belong To
Groups from groups sizes array
10.09.2023
hard1359. Count All Valid Pickup and Delivery Options
Count permutations of the n pickup -> delivery orders
9.09.2023
medium377. Combination Sum IV
Number of ways to sum up array nums to target
8.09.2023
easy118. Pascal's Triangle
Pascal Triangle
7.09.2023
medium92. Reverse Linked List II
Reverse a part of Linked List
6.09.2023
medium725. Split Linked List in Parts
Split Linked List into k almost equal lists
5.09.2023
medium138. Copy List with Random Pointer
Copy of a graph
4.09.2023
easy141. Linked List Cycle
Detect a cycle in a LinkedList
3.09.2023
medium62. Unique Paths
Unique paths count, moving right-down from top-left to bottom-right
2.09.2023
medium2707. Extra Characters in a String
Min count of leftovers after string split by the dictionary
1.09.2023
easy338. Counting Bits
Array of bits count for numbers 0..n
31.08.2023
hard1326. Minimum Number of Taps to Open to Water a Garden
Fill all space between 0..n using minimum intervals
30.08.2023
hard2366. Minimum Replacements to Sort the Array
Minimum number of number splits to make an array non-decreasing
29.08.2023
medium2483. Minimum Penalty for a Shop
First index of minimum penalty in array, penalty 'Y'-> 1, 'N' -> -1
28.08.2023
easy225. Implement Stack using Queues
Create a Stack using Queue's push/pop methods.
27.08.2023
hard403. Frog Jump
Can jump an array when each jump is k-1..k+1 of the previous
26.08.2023
medium646. Maximum Length of Pair Chain
Max count non-overlaping intervals
25.08.2023
medium97. Interleaving String
Can a string be a merge of two other strings
24.08.2023
hard68. Text Justification
Spread words to lines, evenly spacing left->right, and left-spacing the last line
23.08.2023
medium767. Reorganize String
Create non repeated subsequent chars string from string
22.08.2023
easy168. Excel Sheet Column Title
Excel col number to letter-number 1 -> A, 28 -> AB
21.08.2023
easy459. Repeated Substring Pattern
careful to not shift by whole length
20.08.2023
hard1203. Sort Items by Groups Respecting Dependencies
Sort items by groups and in groups given dependencies.
19.08.2023
hard1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
List of list of must-have edges and list of optional edges for Minimum Weight Minimum Spanning Tree
18.08.2023
medium1615. Maximal Network Rank
Max edges count for each pair of nodes
17.08.2023
medium542. 01 Matrix
Distances to 0 in an 0-1 matrix
16.08.2023
medium239. Sliding Window Maximum
List of sliding window's maximums
15.08.2023
medium86. Partition List
Partition a Linked List by x value
14.08.2023
medium215. Kth Largest Element in an Array
Kth largest in an array
13.08.2023
medium2369. Check if There is a Valid Partition For The Array
Is it possible to partition an array of 2 or 3 equal nums or 3 increasing nums.
12.08.2023
medium63. Unique Paths II
Number of right-down ways tl->br in a matrix with obstacles
11.08.2023
medium518. Coin Change II
Ways to make amount with array of coins
10.08.2023
medium81. Search in Rotated Sorted Array II
Binary Search in a rotated array with duplicates
09.08.2023
medium2616. Minimize the Maximum Difference of Pairs
Minimum of maximums possible p diffs of distinct array positions
08.08.2023
medium33. Search in Rotated Sorted Array
Binary Search in a shifted array
07.08.2023
medium74. Search a 2D Matrix
D Binary Search
06.08.2023
hard920. Number of Music Playlists
Playlists number playing n songs goal times, repeating each once in a k times
05.08.2023
medium95. Unique Binary Search Trees II
All possible Binary Search Trees for 1..n numbers
04.08.2023
medium139. Word Break
If a word is a wordDict concatenation
03.08.2023
medium17. Letter Combinations of a Phone Number
Possible words from phone keyboard
02.08.2023
medium46. Permutations
List of all numbers permutations
01.08.2023
medium77. Combinations
All combinations choosing k numbers from 1..n numbers
31.07.2023
medium712. Minimum ASCII Delete Sum for Two Strings
Minimum removed chars sum to make strings equal
30.07.2023
hard664. Strange Printer
Minimum continuous overrides by the same character to make a string
29.07.2023
medium808. Soup Servings
Probability of soup A drained first or both A and B with 0.5 multiplier.
28.07.2023
medium486. Predict the Winner
Optimally taking numbers from an array's ends can one player win another
27.07.2023
hard2141. Maximum Running Time of N Computers
Maximum time to use n batteries in parallel
26.07.2023
medium1870. Minimum Speed to Arrive on Time
Max speed for all dist departing at round hours, be fit in hour
25.07.2023
medium852. Peak Index in a Mountain Array
Mountain pattern index in the array in log time
24.07.2023
medium50. Pow(x, n)
x^n
23.07.2023
medium894. All Possible Full Binary Trees
All possible Full Binary Trees with n nodes, each have both children
22.07.2023
medium688. Knight Probability in Chessboard
Probability of making k steps on a chessboard without stepping outside
21.07.2023
medium673. Number of Longest Increasing Subsequence
use an array cache, as Map gives TLE
20.07.2023
medium735. Asteroid Collision
Result after asteroids collide left-right exploding by size: 15 5 -15 -5 5 -> -15 -5 5
19.07.2023
medium435. Non-overlapping Intervals
Minimum intervals to erase overlap
18.07.2023
medium146. LRU Cache
use firstNode and lastNode
17.07.2023
medium445. Add Two Numbers II
Linked List of sum of two Linked Lists numbers, 9->9 + 1 = 1->0->0
16.07.2023
hard1125. Smallest Sufficient Team
Smallest team from people with skills, having all required skills
15.07.2023
hard1751. Maximum Number of Events That Can Be Attended II
Max sum of at most k values from non-intersecting array of (from, to, value) items
14.07.2023
medium1218. Longest Arithmetic Subsequence of Given Difference
Longest arithmetic difference subsequence
13.07.2023
medium207. Course Schedule
If none edges in a cycle
12.07.2023
medium802. Find Eventual Safe States
List of nodes not in cycles
12.07.2023
medium863. All Nodes Distance K in Binary Tree
List of k distanced from target nodes in a Binary Tree
11.07.2023
easy111. Minimum Depth of Binary Tree
Count nodes in the shortest path from root to leaf
10.07.2023
hard2272. Substring With Largest Variance
Max diff between count s[i] and count s[j] in all substrings of s
9.07.2023
hard2551. Put Marbles in Bags
abs(max - min), where max and min are the sum of k interval borders
7.07.2023
medium2024. Maximize the Confusion of an Exam
Max same letter subarray replacing k letters
6.07.2023
medium209. Minimum Size Subarray Sum
Min length subarray with sum >= target
5.07.2023
medium1493. Longest Subarray of 1's After Deleting One Element
Largest 1..1 subarray after removing one item
4.07.2023
medium137. Single Number II
Let's use fold.
3.07.2023
easy859. Buddy Strings
Is it just one swap s[i]<>s[j] to string s == string goal
2.07.2023
hard1601. Maximum Number of Achievable Transfer Requests
Max edges to make all counts in == out edges in graph
1.07.2023
medium2305. Fair Distribution of Cookies
Min of the max distributing n cookies to k children
30.06.2023
hard1970. Last Day Where You Can Still Cross
Last day matrix connected top-bottom when flooded each day at cells[day]
29.06.2023
hard864. Shortest Path to Get All Keys
Min steps to collect all lowercase keys in matrix. # and uppercase locks are blockers.
28.06.2023
medium1514. Path with Maximum Probability
Max probability path from start to end in a probability edges graph
27.06.2023
medium373. Find K Pairs with Smallest Sums
List of increasing sum pairs a[i], b[j] from two sorted lists a, b
26.06.2023
medium2462. Total Cost to Hire K Workers
The sum of the smallest cost from suffix and prefix of a costs size of candidates in k iterations
25.06.2023
hard1575. Count All Possible Routes
Count paths from start to finish using |locations[i]-locations[j] of the fuel
24.06.2023
hard956. Tallest Billboard
Max sum of disjoint set in array
23.06.2023
medium1027. Longest Arithmetic Subsequence
Max arithmetic subsequence length in array
22.06.2023
medium714. Best Time to Buy and Sell Stock with Transaction Fee
Max profit from buying stocks and selling them with fee for prices[day]
21.06.2023
hard2448. Minimum Cost to Make Array Equal
Min cost to make all arr[i] equal, where each change is cost[i]
20.06.2023
medium2090. K Radius Subarray Averages
Array containing sliding window of size 2k+1 average or -1
19.06.2023
easy1732. Find the Highest Altitude
Max running sum
18.06.2023
hard2328. Number of Increasing Paths in a Grid
Count increasing paths in a matrix
17.06.2023
hard1187. Make Array Strictly Increasing
Minimum replacements to make arr1 increasing using any numbers arr2
16.06.2023
hard1569. Number of Ways to Reorder Array to Get Same BST
Count permutations of an array with identical Binary Search Tree
15.06.2023
medium1161. Maximum Level Sum of a Binary Tree
Binary Tree level with max sum
14.06.2023
easy530. Minimum Absolute Difference in BST
Min difference in a BST
13.06.2023
medium2352. Equal Row and Column Pairs
Count of rowArray == colArray in an n x n matrix.
12.06.2023
easy228. Summary Ranges
Fold continues ranges in a sorted array 1 2 3 5 -> 1->3, 5
11.06.2023
medium1146. Snapshot Array
Implement an array where all elements can be saved into a `snapshot's.
10.06.2023
medium1802. Maximum Value at a Given Index in a Bounded Array
Max at index in an n sized array, where sum <= maxSum, nums[i] > 0 and maxDiff(i, i+1) < 2.
09.06.2023
easy744. Find Smallest Letter Greater Than Target
Lowest char greater than target.
08.06.2023
easy1351. Count Negative Numbers in a Sorted Matrix
Count negatives in a sorted by row and by column matrix.
07.06.2023
medium1318. Minimum Flips to Make a OR b Equal to c
Minimum a and b Int bit flips to make a or b == c.
06.06.2023
easy1502. Can Make Arithmetic Progression From Sequence
Is IntArray can be arithmetic progression?
05.06.2023
easy1232. Check If It Is a Straight Line
Are all the x,y points in a line?
04.06.2023
medium547. Number of Provinces
Count connected groups in graph.
03.06.2023
medium1376. Time Needed to Inform All Employees
Total time from headID to all nodes in graph.
02.06.2023
medium2101. Detonate the Maximum Bombs
Count detonated bombs by chain within each radius.
01.06.2023
medium1091. Shortest Path in Binary Matrix
0 path length in a binary square matrix.
31.05.2023
medium1396. Design Underground System
Average time from, to when different user IDs do checkIn(from, time1) and checkOut(to, time2)
30.05.2023
easy705. Design HashSet
Write a HashSet.
29.05.2023
easy1603. Design Parking System
Return if car of type 1, 2 or 3 can be added given sizes big, medium and small.
28.05.2023
hard1547. Minimum Cost to Cut a Stick
Min cost of cuts c1,..,ci,..,cn of [0..n] where cut cost the length = to-from.
27.05.2023
hard1406. Stone Game III
Winner of “Alice”, “Bob” or “Tie” in game of taking 1, 2 or 3 stones by turn from stoneValue array.
26.05.2023
medium1140. Stone Game II
While Alice and Bob optimally take 1..2 m numbers from piles find maximum for Alice.
25.05.2023
medium837. New 21 Game
Probability sum of random numbers 1..maxPts sum be < n after it overflow k.
24.05.2023
medium2542. Maximum Subsequence Score
Max score of k sum(subsequence(a)) min(subsequence(b))
23.05.2023
medium703. Kth Largest Element in a Stream
Kth largest
22.05.2023
medium347. Top K Frequent Elements
First k unique elements sorted by frequency.
21.05.2023
medium934. Shortest Bridge
Find the shortest path from one island of 1's to another.
20.05.2023
medium399. Evaluate Division
Given values for a/b and b/c find answers for a/c.
19.05.2023
medium785. Is Graph Bipartite?
Find if graph is bipartite
18.05.2023
medium1557. Minimum Number of Vertices to Reach All Nodes
Find all starting nodes in graph.
17.05.2023
medium2130. Maximum Twin Sum of a Linked List
Max sum of head-tail twin ListNodes: a-b-c-d -> max(a+d, b+c)
16.05.2023
medium24. Swap Nodes in Pairs
Swap adjacent ListNodes a-b-c-d -> b-a-d-c.
15.05.2023
medium1721. Swapping Nodes in a Linked List
Swap the values of the head-tail k'th ListNodes.
14.05.2023
hard1799. Maximize Score After N Operations
Max indexed-gcd-pair sum from 2n array; [3,4,6,8] -> 11 (1gcd(3,6) + 2gcd(4,8))
13.05.2023
medium2466. Count Ways To Build Good Strings
Let's write a DFS solution, adding zero or one and count the good strings.
12.05.2023
medium2140. Solving Questions With Brainpower
Let's implement a bottom-up solution.
11.05.2023
medium1035. Uncrossed Lines
use an array for the faster cache instead of HashMap
10.05.2023
medium59. Spiral Matrix II
to detect an empty cell, we can check it for == 0
9.05.2023
medium54. Spiral Matrix
do track the borders left, top, right, bottom
8.05.2023
easy1572. Matrix Diagonal Sum
avoid double counting of the center element
7.05.2023
hard1964. Find the Longest Valid Obstacle Course at Each Position
google what is the solution of LIS
6.05.2023
medium1498. Number of Subsequences That Satisfy the Given Sum Condition
Precompute the 2-powers
5.05.2023
medium1456. Maximum Number of Vowels in a Substring of Given Length
we can use Set to check if it is a vowel
4.05.2023
medium649. Dota2 Senate
Use Queue and count how many bans are from the Radiant and from the Dire.
3.05.2023
easy2215. Find the Difference of Two Arrays
One way is to use two Sets and just filter them.
2.05.2023
easy1822. Sign of the Product of an Array
There is an sign function in kotlin, but leetcode.com doesn't support it yet.
1.05.2023
easy1491. Average Salary Excluding the Minimum and Maximum Salary
We can do .fold and iterate only once, but sum, max and min operators are less verbose.
30.04.2023
hard1579. Remove Max Number of Edges to Keep Graph Fully Traversable
Use separate Union-Find objects for Alice and for Bob
29.04.2023
hard1697. Checking Existence of Edge Length Limited Paths
for better time complexity, compress the Union-Find path uf[x] = n
28.04.2023
hard839. Similar String Groups
decrease the groups when the two groups are joined together
27.04.2023
medium319. Bulb Switcher
Use found law and write the code.
26.04.2023
easy258. Add Digits
It is just an array pointer loop shifted by 1.
25.04.2023
medium2336. Smallest Number in Infinite Set
Let's implement a sparse array.
24.04.2023
easy1046. Last Stone Weight
use PriorityQueue with compareByDescending
23.04.2023
hard1416. Restore The Array
use Long to avoid overflow
22.04.2023
hard1312. Minimum Insertion Steps to Make a String Palindrome
Just DFS and cache.
21.04.2023
hard879. Profitable Schemes
Do DFS and cache result in an array.
20.04.2023
medium662. Maximum Width of Binary Tree
We can do BFS and track node positions.
19.04.2023
medium1372. Longest ZigZag Path in a Binary Tree
Compute the max as you go
18.04.2023
easy1768. Merge Strings Alternately
we can use sequence zip operator
17.04.2023
easy1431. Kids With the Greatest Number of Candies
Let's write the code
16.04.2023
hard1639. Number of Ways to Form a Target String Given a Dictionary
precompute the freq array - count of each character at each position
15.04.2023
hard2218. Maximum Value of K Coins From Piles
We can cache the result by the keys of every pile to taken
14.04.2023
medium516. Longest Palindromic Subsequence
For cleaner code
13.04.2023
medium946. Validate Stack Sequences
use one iteration and a second pointer for pop
12.04.2023
medium71. Simplify Path
split the string by /
11.04.2023
medium2390. Removing Stars From a String
we can use a Stack, or just StringBuilder
10.04.2023
medium20. Valid Parentheses
use HashMap to check matching bracket.
09.04.2023
hard1857. Largest Color Value in a Directed Graph
use visited set to detect cycles
08.04.2023
medium133. Clone Graph
we can avoid using visited set by checking if a new node already has filled its neighbors.
07.04.2023
medium1020. Number of Enclaves
We can use visited set, or modify the grid or use Union-Find.
06.04.2023
medium1254. Number of Closed Islands
DFS will solve the problem.
05.04.2023
medium2439. Minimize Maximum of Array
careful with integers overflows
04.04.2023
medium2405. Optimal Partition of String
use hashset, [26] array or simple 32-bit mask to store visited flags for character
03.04.2023
medium881. Boats to Save People
Sort an array and move two pointers lo and hi.
02.04.2023
medium2300. Successful Pairs of Spells and Potions
sort potions
01.04.2023
easy704. Binary Search
For more robust code
31.03.2023
hard1444. Number of Ways of Cutting a Pizza
carefully precompute prefix sum. You move by row, increasing sumX, then you move by column and reuse the result of the previous row.
30.03.2023
hard87. Scramble String
A simple approach is to concatenate strings, but in Kotlin it gives TLE, so we need bottom up approach, or just operate with indices.
29.03.2023
hard1402. Reducing Dishes
The naive $$O(n^2)$$ solution will work. However, there is an optimal one if we simply go from the end.
28.03.2023
medium983. Minimum Cost For Tickets
Let's write DFS with memoization algorithm as it is simple to understand.
27.03.2023
medium64. Minimum Path Sum
Use DFS + memo, careful with the ending condition.
26.03.2023
hard2360. Longest Cycle in a Graph
Use separate visited sets for the current path and for the global visited nodes.
25.03.2023
medium2316. Count Unreachable Pairs of Nodes in an Undirected Graph
use path compression for better root time complexity
24.03.2023
medium1466. Reorder Routes to Make All Paths Lead to the City Zero
We can use data structure or just use sign to encode the direction.
23.03.2023
medium1319. Number of Operations to Make Network Connected
for the better time complexity of the findRoot use path compression: uf[x] = n
22.03.2023
medium2492. Minimum Score of a Path Between Two Cities
Connect all roads and update minimums in the Union-Find data structure. Use simple arrays for both connections and minimums.
21.03.2023
medium2348. Number of Zero-Filled Subarrays
We can count subarray sums, then add them to the result, or we can just skip directly to adding to the result.
20.03.2023
easy605. Can Place Flowers
careful with corner cases
19.03.2023
medium211. Design Add and Search Words Data Structure
Let's try to write it in a Kotlin way, using as little words as possible.
18.03.2023
medium1472. Design Browser History
Just implement it.
17.03.2023
medium208. Implement Trie (Prefix Tree)
Let's try to write it Kotlin-way
16.03.2023
medium106. Construct Binary Tree from Inorder and Postorder Traversal
To more robust code, consider moving postTo variable as we go in the reverse-postorder: from the right to the left.
15.03.2023
medium958. Check Completeness of a Binary Tree
Right depth must not be larger than left.
14.03.2023
medium129. Sum Root to Leaf Numbers
The most trivial way is to keep sum variable outside the dfs function.
13.03.2023
easy101. Symmetric Tree
Recursive: just write helper function.
12.03.2023
hard23. Merge k Sorted Lists
use dummy head
11.03.2023
medium109. Convert Sorted List to Binary Search Tree
Compute the middle of the linked list.
10.03.2023
medium382. Linked List Random Node
Write the naive solution, then go to Wikipedia, and hope you will not get this in the interview.
09.03.2023
medium142. Linked List Cycle II
careful with corner cases.
08.03.2023
medium875. Koko Eating Bananas
For more robust binary search
07.03.2023
medium2187. Minimum Time to Complete Trips
Do a binary search. For the hi value, we can peak a $$10^7$$ or just compute all the time it takes for every bus to trip.
06.03.2023
easy1539. Kth Missing Positive Number
For more robust binary search code
05.03.2023
hard1345. Jump Game IV
This problem gives TLE until we do one trick
04.03.2023
hard2444. Count Subarrays With Fixed Bounds
For the explicit solution, we take each interval, store positions of the min and max in a TreeSet, then we must take poll those mins and maxes and consider each range separately
03.03.2023
medium28. Find the Index of the First Occurrence in a String
carefull with indexes
02.03.2023
medium443. String Compression
Let's just do a naive toString for simplicity.
01.03.2023
medium912. Sort an Array
Let's just implement naive quicksort.
28.02.2023
medium652. Find Duplicate Subtrees
Let's use pre-order traversal and serialize each node into string, also add that into HashSet and check for duplicates.
27.02.2023
medium427. Construct Quad Tree
use inclusive ranges to simplify the code
26.02.2023
hard72. Edit Distance
Do DFS and use array for memoizing the result.
25.02.2023
easy121. Best Time to Buy and Sell Stock
we can just use current value as a max candidate instead of managing the max variable.
24.02.2023
hard1675. Minimize Deviation in Array
Use TreeSet to quickly access to the min and max elements.
23.02.2023
hard502. IPO
Sort items by increasing capital. Then, on each step, add all possible deals to the priority queue and take one best from it.
22.02.2023
medium1011. Capacity To Ship Packages Within D Days
To more robust binary search code
21.02.2023
medium540. Single Element in a Sorted Array
Let's write a binary search. For more robust code, consider
20.02.2023
easy35. Search Insert Position
For more robust code consider
19.02.2023
medium103. Binary Tree Zigzag Level Order Traversal
for zigzag, we can skip a boolean variable and track result count.
18.02.2023
easy226. Invert Binary Tree
Let's write a recursive one-liner.
17.02.2023
easy783. Minimum Distance Between BST Nodes
Let's write Morris Traversal. Store current node at the rightmost end of the left children.
16.02.2023
easy104. Maximum Depth of Binary Tree
Let's write a one-liner.
15.02.2023
easy989. Add to Array-Form of Integer
use linked list to add to the front of the list in O(1)
14.02.2023
easy67. Add Binary
keep track of the overflow
13.02.2023
easy1523. Count Odd Numbers in an Interval Range
fun countOdds(low: Int, high: Int): Int {
12.02.2023
medium2477. Minimum Fuel Cost to Report to the Capital
Use DFS and data class for the result.
11.02.2023
medium1129. Shortest Path with Alternating Colors
Start with two simultaneous points, one for red and one for blue. Keep track of the color.
10.02.2023
medium1162. As Far from Land as Possible
Add all land cells into BFS, then just run it.
9.02.2023
hard2306. Naming a Company
Group and multiply. Don't forget to remove repeating elements in each two groups.
8.02.2023
medium45. Jump Game II
use stack to store jumps
7.02.2023
medium904. Fruit Into Baskets
careful with corner cases
6.02.2023
easy1470. Shuffle the Array
For simplicity, use two pointers for the source, and one for the destination.
5.02.2023
medium438. Find All Anagrams in a String
To avoid checking a frequencies arrays, we can count how many frequencies are not matching, and add only when non-matching count is zero.
4.02.2023
medium567. Permutation in String
to decrease cost of comparing arrays, we can also use hashing
3.02.2023
medium6. Zigzag Conversion
Store simulation result in a [rowsNum][simulation indice] - matrix, then build the result.
2.02.2023
easy953. Verifying an Alien Dictionary
Just translate and then sort and compare. (But we can also just scan linearly and compare).
1.02.2023
easy1071. Greatest Common Divisor of Strings
We can first find the length of the greatest common divisor, then just check both strings.
31.01.2023
medium1626. Best Team With No Conflicts
We can use DFS to search all the possible teams and memorize the result in dp cache.
30.01.2023
easy1137. N-th Tribonacci Number
another way is to use dp cache
29.01.2023
hard460. LFU Cache
one thing to note, on each increaseFreq operation we are retrieving a random item from TreeMap, that increases time to O(log(F)), where F is a unique set of frequencies.
28.01.2023
hard352. Data Stream as Disjoint Intervals
careful with merge
27.01.2023
hard472. Concatenated Words
first, scan all the words, and fill the Trie
26.01.2023
medium787. Cheapest Flights Within K Stops
by the problem definition, path length is k+1, not just k
25.01.2023
medium2359. Find Closest Node to Given Two Nodes
fun closestMeetingNode(edges: IntArray, node1: Int, node2: Int): Int {
24.01.2023
medium909. Snakes and Ladders
fun snakesAndLadders(board: Array
23.01.2023
easy997. Find the Town Judge
fun findJudge(n: Int, trust: Array
22.01.2023
medium131. Palindrome Partitioning
fun partition(s: String): List> {
21.01.2023
medium93. Restore IP Addresses
fun restoreIpAddresses(s: String): List
20.01.2023
medium491. Non-decreasing Subsequences
fun findSubsequences(nums: IntArray): List> {
19.01.2023
medium974. Subarray Sums Divisible by K
fun subarraysDivByK(nums: IntArray, k: Int): Int {
18.01.2023
medium918. Maximum Sum Circular Subarray
fun maxSubarraySumCircular(nums: IntArray): Int {
17.01.2023
medium926. Flip String to Monotone Increasing
fun minFlipsMonoIncr(s: String): Int {
16.01.2023
medium57. Insert Interval
fun insert(intervals: Array
15.01.2023
hard2421. Number of Good Paths
fun numberOfGoodPaths(vals: IntArray, edges: Array
14.01.2023
medium1061. Lexicographically Smallest Equivalent String
fun smallestEquivalentString(s1: String, s2: String, baseStr: String): String {
13.01.2023
hard2246. Longest Path With Different Adjacent Characters
fun longestPath(parent: IntArray, s: String): Int {
12.01.2023
medium1519. Number of Nodes in the Sub-Tree With the Same Label
fun countSubTrees(n: Int, edges: Array
11.01.2023
medium1443. Minimum Time to Collect All Apples in a Tree
fun minTime(n: Int, edges: Array
10.01.2023
easy100. Same Tree
fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean = p == null && q == null ||
9.01.2023
easy144. Binary Tree Preorder Traversal
class Solution {
8.01.2023
hard149. Max Points on a Line
fun maxPoints(points: Array
7.01.2023
medium134. Gas Station
fun canCompleteCircuit(gas: IntArray, cost: IntArray): Int {
6.01.2023
medium1833. Maximum Ice Cream Bars
fun maxIceCream(costs: IntArray, coins: Int): Int {
5.01.2023
medium452. Minimum Number of Arrows to Burst Balloons
fun findMinArrowShots(points: Array
4.01.2023
medium2244. Minimum Rounds to Complete All Tasks
fun minimumRounds(tasks: IntArray): Int {
3.01.2023
easy944. Delete Columns to Make Sorted
fun minDeletionSize(strs: Array
2.01.2023
easy520. Detect Capital
fun detectCapitalUse(word: String): Boolean =
1.01.2023
easy290. Word Pattern
fun wordPattern(pattern: String, s: String): Boolean {