Given an integer array nums, the goal is to determine if any value appears at least twice. The function should return true if a duplicate exists, and false if every element is distinct.
This approach uses a HashSet to efficiently keep track of the numbers encountered while iterating through the input array. A HashSet is an ideal choice here because it only stores unique values and provides very fast (average O(1) time) lookups.
Initialize a Set: An empty HashSet called set is created. This set will store the unique numbers we've seen so far.
Iterate and Check: The code loops through each num in the input array nums. Inside the loop, set.contains(num) checks if the current number is already in our set. If set.contains(num) is true, it means we have seen this number before. We have found a duplicate, so the function immediately returns true and stops executing.
Store Unique Numbers: If the number is not a duplicate (i.e., set.contains(num) was false), it gets added to the set via set.add(num). This ensures we can check for it in future iterations.
No Duplicates Found: If the loop finishes without ever finding a duplicate, it means every element in the array was unique. In this case, the function returns false.
Time Complexity: O(N) The code iterates through the array of N elements once. Both set.contains() and set.add() operations take, on average, constant time (O(1)). Therefore, the total time complexity is linear.
Space Complexity: O(N) In the worst-case scenario where all elements in the array are unique, the HashSet will grow to a size of N. Therefore, the space required is proportional to the number of elements in the input array.
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
The solution is based on a classic mathematical trick. Since the input array contains n distinct numbers taken from the range [0, n], exactly one number is missing.
Determine the Expected Sum: If the array were complete, it would contain all integers from 0 to n (where n is nums.length). The sum of a sequence of numbers from 0 to n can be quickly calculated with the Gaussian sum formula: S_n= n(n+1)/2. This gives us the expectedSum.
Calculate the Actual Sum: The code then iterates through the input array nums one time to calculate the actualSum of all the elements it contains.
Find the Missing Number: The difference between the expectedSum and the actualSum is precisely the number that is missing from the sequence. The function returns this difference.
For example, with nums = [3, 0, 1]:
n is 3.
Expected Sum = (3 * (3 + 1)) / 2 = (3 * 4) / 2 = 6. (The sum of 0+1+2+3)
Actual Sum = 3 + 0 + 1 = 4.
Missing Number = 6 - 4 = 2.
Time Complexity:
Space Complexity:
Given an array nums of n integers where each element nums[i] is in the range [1, n], return a list of all the integers in the range [1, n] that do not appear in nums.
This solution uses a HashSet to easily keep track of which numbers are present in the input array.
Store Present Numbers: First, the code iterates through the input array nums and adds every number to a HashSet. A set is used because it automatically handles duplicates and provides very fast lookups (checking if an element exists).
Find Missing Numbers: After building the set of present numbers, the code starts a new loop that iterates through the complete range of numbers from 1 to n (where n is the length of the array).
Collect Results: In this second loop, it checks if each number i is in the HashSet. If presentNumbers.contains(i) returns false, it means the number i was missing from the original array, and it's added to the final result list.
Time Complexity:
Space Complexity:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 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.
The core idea is that for each number x in the array, you're looking for a complement number y such that x + y = target. This means y = target - x.
By using a HashMap, you can check for this complement in constant time.
Initialize a HashMap: Create a HashMap to store (number, index) pairs.
Iterate Through the Array: Loop through the nums array one element at a time.
Check for a Solution: For each number nums[i]:
Calculate its required complement: complement = target - nums[i].
Check if the complement already exists as a key in the HashMap.
If it does, you've found the solution. Return the complement's index (which you get from the map) and the current number's index, i.
If it doesn't, add the current number nums[i] and its index i to the map. This stores it for future checks.
This one-pass approach is efficient because you're both checking for a solution and building up the map of potential complements at the same time.
Time Complexity:
Space Complexity:
Imagine you're given a list of numbers. Your goal is to create a new list of the exact same size.
For every number in the original list, you need to look through the entire list and count how many of the other numbers are smaller than it. The result of that count will be the new value at that same position.
This method provides a significant improvement over the brute-force approach. The core idea is to sort a copy of the array. Once sorted, the index of a number tells you how many elements are smaller than or equal to it. We use a HashMap to efficiently store this information and handle duplicates.
Create a Copy and Sort: First, we create a copy of the original nums array. We need the original order for our final result, so we must sort the copy, not the input array itself.
Map Numbers to Counts: We create a HashMap to store each unique number and its corresponding count of smaller numbers. We iterate through the sorted array. The index i of a number in the sorted array is the count of how many numbers are smaller than it.
For example, in the sorted array [1, 2, 2, 3, 8]:
The first number is 1 at index 0, so 0 numbers are smaller than it.
The first 2 is at index 1, so 1 number is smaller than it.
The number 3 is at index 3, so 3 numbers are smaller than it.
We only put a number into the map the first time we see it. This correctly handles duplicates, ensuring that all instances of 2 are mapped to a count of 1 (the index of the first 2).
Build the Final Result: Finally, we iterate through the original nums array. For each number, we look up its pre-calculated count in our map and place it in the corresponding position in our result array.
Time Complexity:
Space Complexity:
On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.
This solution calculates the total travel time by breaking the journey down into smaller segments, moving from one point to the next in the specified order. It cleverly maintains the location of the "previous" point to calculate the time for each step.
Initialization: The code starts by initializing the total time (minTime) to 0 and setting the starting coordinates (x1, y1) to the very first point in the list (points[0]).
Iterating Through Segments: It then iterates through the rest of the points, from the second point (i = 1) to the end. In each step of the loop, it treats (x1, y1) as the starting point and points[i] as the destination for that segment.
Calculating Segment Time: As your own comments correctly derive, the minimum time to travel between any two points is the Chebyshev distance. This is the greater of the horizontal distance (dx) and the vertical distance (dy). The line minTime += Math.max( Math.abs( x2-x1 ), Math.abs( y2-y1 ) ); efficiently calculates this time and adds it to the running total.
Updating State: After calculating the time to get to the current point (x2, y2), the code updates the "previous" point by setting x1=x2 and y1=y2. This prepares for the next iteration, where the current point will become the starting point for the next segment.
This process continues until all segments have been traveled, resulting in the total minimum time.
Time Complexity:
Space Complexity:
Given an m x n matrix, return all elements of the matrix in spiral order. Input: matrix = [ [1,2,3],[4,5,6],[7,8,9] ] Output: [1,2,3,6,9,8,7,4,5]
code solves the problem by simulating a spiral traversal of the matrix. It "peels" the matrix layer by layer from the outside in, using four pointers to keep track of the boundaries of the current layer.
Initialization: top, bottom, left, right: You initialize four integer variables to define the boundaries of the matrix. top and left start at 0, while bottom and right start at the last row and column indices, respectively.
result: An ArrayList is created to store the numbers in their spiral order.
Main Traversal Loop: The while(top <= bottom && left <= right) loop is the core of the algorithm. It ensures that the process continues as long as there is a valid layer to traverse (i.e., the top boundary is not below the bottom, and the left is not past the right).
The Four Traversal Steps: Inside the while loop, one full spiral layer is traversed in four distinct steps:
- Step 1 (Go Right): The first for loop iterates from left to right along the top row, adding each element to the result list. Afterward, top is incremented, effectively moving the top boundary down.
- Step 2 (Go Down): The second for loop traverses down the right column from the new top to bottom. Afterward, right is decremented, shrinking the boundary inward.
- Step 3 (Go Left): Before traversing left, the crucial if (top <= bottom) check ensures there's still a valid row to traverse. This prevents errors on "thin" matrices (e.g., a single column). If valid, it traverses from right to left along the bottom row, and then bottom is decremented.
- Step 4 (Go Up): Similarly, the if (left <= right) check ensures a valid column exists before traversing up the left column. If valid, it traverses from bottom to top, and then left is incremented. This cycle repeats, with the boundaries shrinking inward, until the while loop condition is no longer met, at which point every element has been visited.
Time Complexity:
Space Complexity: $O(1) The space required by the algorithm itself is constant. The variables top, bottom, left, right, and the loop counters do not depend on the size of the input matrix.
(Note: If you consider the space required for the output result list, the space complexity would be
Given an m x n 2D binary grid, grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
The Depth-First Search strategy explores an island by going as deep as possible down one path before backtracking.
1. Main Loop: The code iterates through every cell of the grid.
2. Island Discovery: If it finds a land cell ('1') that has not been previously visited, it knows it has found a new, distinct island. It increments the islandCount.
3. Recursive Exploration: It then calls a recursive dfs helper function starting from that cell.
-
The dfs function first marks the current cell as visited.
-
It then calls itself for all four of its neighbors (up, down, left, right).
-
The recursion stops for a given path if it goes out of bounds, hits water, or reaches a cell that has already been visited.
4. Completion: This recursive process continues until every connected part of the newly discovered island has been marked as visited. The main loop then continues its scan, ignoring the now-visited cells, until it finds the next unvisited island.
The Breadth-First Search strategy explores an island layer by layer, visiting all of a cell's immediate neighbors before moving on to the next level.
1. Main Loop: The main loop is identical to the one in the DFS approach. It scans for an unvisited land cell ('1') and increments the islandCount upon finding one.
2. Queue-Based Exploration: Instead of using recursion, BFS uses a Queue data structure to manage the exploration.
-
When a new island is discovered, its starting cell is added to the queue and immediately marked as visited.
-
A while loop runs as long as the queue is not empty.
-
Inside the loop, a cell is removed from the front of the queue. Its valid, unvisited land neighbors are then marked as visited and added to the back of the queue.
3. Completion: The while loop finishes once the queue is empty, which means every connected cell in the island has been visited. The main loop then continues its scan.
For this problem, the complexity is the same for both the DFS and BFS solutions.
Time Complexity:
Space Complexity:
-
DFS uses the call stack for recursion, which in the worst case (a long, snake-like island) could also be
$O(M \times N)$ . -
BFS uses a Queue, which in the worst case (a very wide island) could hold up to O(min(M,N)) elements.
-
However, since the visited array is always required in this non-destructive approach, the overall space complexity is considered
$O(M \times N)$ .
You are given an array prices where prices[i] is the price of a given stock on the i^th day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
This algorithm efficiently finds the maximum profit in a single pass using a greedy, two-pointer approach. The strategy is to always make the locally optimal choice at each step, hoping it leads to the globally optimal solution.
Initialization:
-
A left pointer is set to day 0, representing our initial "buy" day.
-
A right pointer is set to day 1 to explore subsequent "sell" days.
-
maxProfit is initialized to 0.
Greedy Choice: The algorithm iterates with the right pointer. At each day, it makes a greedy choice:
-
Is it profitable now? (
prices[right] > prices[left])If the current price is higher than our buy price, the locally optimal move is to see if this transaction yields the best profit so far. We calculate the profit and update
maxProfitif necessary. -
Is there a better buy price? (
prices[right] <= prices[left])If the current price is lower than our buy price, it's impossible for our old buy day to ever be part of a better future profit. The greedy choice is to immediately abandon the old buy day and update our buy day to this new, lower price (
left = right). We greedily take the lowest price we can get for a buy day, as this gives us the maximum potential for future profit.
By always keeping the left pointer at the lowest price seen so far, we ensure that any profit we calculate is always the maximum possible profit for that specific sell day.
-
Time Complexity:
$O(N)$ The algorithm is greedy because it makes its decision based on the current best information without looking ahead or behind. Since the right pointer visits each element only once, the time complexity is linear. -
Space Complexity:
$O(1)$ The solution only uses a few constant variables (left, right, maxProfit). The memory usage does not grow with the size of the input array.
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
The core insight is that after squaring, the largest values will always come from the numbers with the largest absolute values, which are at the ends of the sorted input array.
-
Initialize Pointers: The algorithm sets up two pointers:
leftat the beginning of the array andrightat the end. It also creates aresultarray of the same size. -
Compare and Place: It compares the square of the number at the
leftpointer with the square of the number at therightpointer. -
Fill from the End: Whichever square is larger is placed at the end of the
resultarray. The corresponding pointer (leftorright) is then moved inward. -
Repeat: This process repeats, filling the
resultarray from right to left with progressively smaller squares until the pointers cross.
Time Complexity: left and right pointers move towards each other. This makes the runtime linear with respect to the size of the input array.
Space Complexity: $O(1)
This solution is very memory-efficient. It only uses a few variables for the pointers, so the extra space is constant. (This excludes the result array, which is required for the output).
This method manually separates the negative and positive numbers, squares them, and then merges them back together.
-
Find Pivot: It first finds the index of the first non-negative number, which acts as a "pivot" to split the array.
-
Create Temporary Arrays: It creates two new arrays:
a: Stores the squares of the negative numbers. They are added in reverse to make this array sorted.
b: Stores the squares of the non-negative numbers, which are already in sorted order.
-
Merge: It then performs a classic "merge" step, similar to merge sort. It iterates through both temporary arrays (a and b), picking the smaller element from the front of either array to place into the final result array.
Time Complexity:
Space Complexity:
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
The strategy is to iterate through the array with one pointer (i) and, for each element nums[i], use two more pointers (left and right) to find two other numbers that sum up to -nums[i].
-
Sort the Input Array: First, sort the
numsarray. This is essential. It makes finding pairs much faster and helps us handle duplicate triplets easily. -
Iterate with the First Pointer: Loop through the sorted array with a pointer
ifrom the beginning up to the third-to-last element. Thisnums[i]will be the first number in our potential triplet.- Skip Duplicates: To avoid duplicate triplets (like
[-1, 0, 1]appearing twice), we add a check. If the current numbernums[i]is the same as the previous onenums[i-1], we skip it and continue to the next iteration.
- Skip Duplicates: To avoid duplicate triplets (like
-
Two-Pointer Scan: For each
nums[i], we set up two more pointers:-
leftstarts right afteri(ati + 1). -
rightstarts at the very end of the array. -
We then loop as long as
left < right, looking for two numbers that, when added tonums[i], equal zero.
-
-
Check the Sum: Inside this inner loop, we calculate
sum = nums[i] + nums[left] + nums[right].-
If
sum == 0: We've found a valid triplet! We add[nums[i], nums[left], nums[right]]to our result list. Then, we must move our pointers past any duplicates of the currentleftandrightvalues to avoid adding the same triplet again. Finally, we moveleftforward andrightbackward to look for new pairs. -
If
sum < 0: The sum is too small, so we need a larger number. We move theleftpointer to the right (left++). -
If
sum > 0: The sum is too large, so we need a smaller number. We move therightpointer to the left (right--).
-
This process continues until the main loop is finished.
Time Complexity:
Space Complexity:
You may recall that an array arr is a mountain array if and only if:
arr.length >= 3
There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.
This Solution uses a "Find Peak and Expand" strategy. It iterates through the array to identify every potential peak and then expands outwards from each one to measure the length of the mountain.
Find a Peak: The main for loop iterates through the array from the second element to the second-to-last element. The if statement if(arr[i] > arr[i-1] && arr[i] > arr[i+1]) correctly identifies if the current element arr[i] is a peak (i.e., it's strictly greater than both of its neighbors).
Expand Outwards: Once a peak is found at index i, the code uses two while loops to find the full extent of the mountain:
-
Expand Left: A
leftpointer, starting at the peak, moves backwards(left--)as long as it's part of an uphill slope(arr[left] > arr[left-1]). This finds the start of the mountain. -
Expand Right: A
rightpointer, also starting at the peak, moves forwards (right++) as long as it's part of a downhill slope(arr[right] > arr[right+1]). This finds the end of the mountain.
Calculate and Update Max Length: After finding the start (left) and end (right) of the mountain, the total length is calculated as right - left + 1. The code then updates the result with this length if it's the longest one found so far using Math.max(result, ...).
The Key Optimization - Skip Ahead: The most clever part of your refined solution is the line i = right;.
-
After a mountain has been fully measured, you already know that the elements on its downhill slope cannot be new peaks.
-
By setting the main loop's counter
iequal toright, you jump the search forward to the end of the mountain you just found. -
This ensures that each element in the array is processed only once, turning the algorithm into a highly efficient single-pass solution.
This process repeats for every possible peak in the array, ensuring the longest mountain is always found.
Time Complexity: while loops inside a for loop, the time complexity is still linear. This is because each element of the array is visited a constant number of times. The main pointer i visits each element once, and the left and right pointers also scan over each element at most once across all iterations. Therefore, the total work is proportional to the size of the array, N.
Space Complexity: result, i, left, right) to store pointers and the maximum length. The amount of memory used does not grow with the size of the input array, so the space complexity is constant.
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
This solution uses a HashSet to maintain a "sliding window" of the most recent unique elements. This window is never larger than size k, which allows the algorithm to efficiently check for duplicates within the required distance.
Initialize a HashSet: The algorithm creates a HashSet, which will act as our sliding window. A HashSet is used because it only stores unique items and can check for an element's existence in constant time.
Iterate and Check: The code iterates through the nums array one element at a time. For each number, it tries to add it to the HashSet.
-
Find a Duplicate in the Window: The
.add()method of aHashSetreturnsfalseif the element already exists in the set. If this happens, it means we have found a duplicate of the current number within our window. Since the window's size is controlled to be no more thank, this duplicate is guaranteed to be nearby, so the function immediately returnstrue. -
Maintain the Window: After processing each element, the code ensures the window doesn't get too large. If the size of the
HashSetexceedsk, the oldest element in the window(nums[i - k])is removed. This action effectively "slides" the window one position to the right, maintaining a constant size and ensuring it only contains recent elements.
If the loop completes without ever finding a duplicate within the sliding window, it means no nearby duplicate exists, and the function returns false.
Time Complexity: $O(N)$
The algorithm iterates through the array of size N exactly once. The operations performed inside the loop—add and remove on the HashSet—both take constant $O(1)$ time on average. This results in a linear time complexity.
Space Complexity: $O(min(N, k))$
The space is determined by the size of the HashSet. The set stores the elements within the "sliding window," which never contains more than k elements. If the total number of elements N is less than k, the set will only store up to N elements. Therefore, the space required is proportional to the smaller of the two values, N and k.
Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows
a, bare fromarra < bb - aequals to the minimum absolute difference of any two elements inarr
Your solution uses an efficient, two-pass approach that hinges on one key insight: after an array is sorted, the minimum difference between any two numbers will always be between adjacent elements.
Sort the Array: The first and most crucial step is Arrays.sort(arr). This operation arranges the numbers in non-decreasing order, which guarantees that elements with the smallest possible differences are now next to each other. This avoids the need to compare every number with every other number.
First Pass (Find the Minimum Difference): The code then iterates through the sorted array once. Its only goal during this pass is to find the single smallest difference between any adjacent pair. It does this by comparing the difference of each pair (arr[i+1] - arr[i]) to the minDifference found so far and updating it whenever a smaller one is found.
Second Pass (Collect the Pairs): Now that the smallest possible difference is known, the code iterates through the sorted array a second time. In this pass, it checks the difference of each adjacent pair again. If a pair's difference is exactly equal to the minDifference, that pair is added to the final result list.
Time Complexity:
Space Complexity: Arrays.sort()for primitives is a variation of Quicksort that requires
Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Initialize Pointers and Sum: We start with both a left and right pointer at the beginning of the array (index 0). We also initialize a currentSum to 0 and a minLength to a very large value (like Integer.MAX_VALUE).
Expand the Window: We iterate through the array with the right pointer, adding each new element to our currentSum. This expands our window to the right.
Shrink the Window: As soon as our currentSum becomes greater than or equal to the target, we've found a valid subarray. Now, we try to find the smallest possible valid subarray by shrinking the window from the left.
-
We record the current window's length (
right - left + 1) if it's smaller than ourminLengthso far. -
We then subtract the element at the
leftpointer fromcurrentSumand move theleftpointer one step to the right. -
We repeat this shrinking process until
currentSumis no longer greater than or equal to thetarget.
Continue: The right pointer continues moving to the right, and the process of expanding and shrinking repeats until we've checked the entire array.
Final Result: If minLength was never updated, it means no valid subarray was found, so we return 0. Otherwise, we return the minLength we found.
Time Complexity: while loop, the algorithm is linear. Each element is visited at most twice—once by the right pointer and once by the left pointer.
Space Complexity:
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
The entire strategy is built on two fundamental properties of the XOR operation:
-
XORing a number with itself results in zero (A ^ A = 0).
-
XORing a number with zero results in the number itself (A ^ 0 = A).
Because the XOR operation is commutative and associative, the order in which you XOR the numbers doesn't matter. You can think of the process as rearranging the array so that all the duplicate pairs are next to each other.
When you XOR every number in the array together:
-
Every pair of duplicate numbers (e.g., 1 ^ 1) will cancel each other out and become 0.
-
The single, unique number is then XORed with the result of all those cancellations (which is 0).
-
This leaves you with just the unique number itself.
Example Walkthrough: nums = [4, 1, 2, 1, 2]
Initialize result = 0.
result ^= 4 => result is now 4.
result ^= 1 => result is now 4 ^ 1.
result ^= 2 => result is now 4 ^ 1 ^ 2.
result ^= 1 => result is now 4 ^ 1 ^ 2 ^ 1. Rearranging gives 4 ^ 2 ^ (1 ^ 1), which simplifies to 4 ^ 2 ^ 0.
result ^= 2 => result is now 4 ^ 2 ^ 0 ^ 2. Rearranging gives 4 ^ 0 ^ (2 ^ 2), which simplifies to 4 ^ 0 ^ 0.
The final result is 4.
Time Complexity:
Space Complexity:
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
We'll use a "bottom-up" dynamic programming approach. The idea is to create an array, let's call it dp, where dp[i] will store the minimum number of coins needed to make the amount i. We'll solve for dp[1], then dp[2], and so on, up to the target amount.
-
Initialize
dpArray: Create an arraydpof sizeamount + 1. We'll fill it with a value that's larger than any possible answer (likeamount + 1) to signify that those amounts are not yet reachable. We setdp[0] = 0because it takes zero coins to make an amount of zero. -
Iterate and Calculate: We loop through each amount
ifrom 1 toamount. For each amount, we check every availablecoin.
-
If a
coinis less than or equal to the current amounti, we have a choice:-
Don't use this coin (the answer is whatever
dp[i]already is). -
Do use this coin. The number of coins would be
1(for the current coin) plusdp[i - coin](the minimum coins needed for the remaining amount).
-
-
We take the minimum of these two choices and store it in
dp[i].
- Final Result: After the loops complete,
dp[amount]will hold the minimum number of coins for the target amount. Ifdp[amount]is still the large value we initialized it with, it means the amount is impossible to make, so we return-1.
Time Complexity: S is the target amount and N is the number of coin denominations. This is because of the nested loops: the outer loop runs S times, and the inner loop runs N times.
Space Complexity: dp array, which is proportional to the amount.
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Use a bottom-up dynamic programming approach that mirrors the Fibonacci pattern. Define an array dp where dp[i] is the number of ways to reach step i.
- Initialize dp
-
Create
dpof sizen + 1. -
Set base values:
dp[1] = 1,dp[2] = 2. -
These bases reflect that to reach step i, you sum ways from the previous one and two steps.
- Iterate and compute
-
For each
ifrom 2 ton, compute:-
Use recurrence:
dp[i] = dp[i - 1] + dp[i - 2]. -
Intuition: reach
ieither fromi-1with a 1-step or fromi-2with a 2-step; add both counts.
-
- Final result
- Return
dp[n], the total distinct ways to reach step n.
Equivalent space-optimized version keeps only the last two values instead of a whole array, since each state depends on the previous two.
Time Complexity: O(n). Single pass from 2 to n, doing O(1) work per step.
Space Complexity: Tabulation: O(n) for the dp array.