Problem On Method
Problem On Method
Given an array height representing the elevation map where the width of each bar is 1, compute
how much water it can trap after raining.
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation:
The elevation map [0,1,0,2,1,0,1,3,2,1,2,1] is represented by vertical bars.
After the rain, the amount of water trapped between the bars is 6 units.
Optimal Approach: Two-Pointer Technique
To solve this problem optimally, you can use a two-pointer technique. The idea is to maintain
two pointers (left and right), and use two variables (leftMax and rightMax) to keep track of the
maximum heights seen from the left and right sides respectively.
Explanation:
Two Pointers (left and right): Start from both ends of the array.
Track Maximum Heights (leftMax and rightMax): As you move the pointers inward,
keep track of the highest bar seen so far from the left and right.
Calculate Water:
o If height[left] < height[right], the trapped water at left depends on leftMax. If
leftMax is greater than height[left], water can be trapped.
o Otherwise, calculate the trapped water using rightMax when height[right] is less
than or equal to height[left].
Move Pointers: Depending on the comparison of heights at left and right, move the
corresponding pointer inward.
Time Complexity:
The time complexity is O(n) where n is the length of the height array. This is because
each element is processed at most once.
Space Complexity:
The space complexity is O(1) since only a few extra variables are used.
This approach is efficient and solves the problem in linear time.
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output:
5
Explanation:
"hit" -> "hot" -> "dot" -> "dog" -> "cog" is a sequence of 5 words.
N-Queens Problem
Problem:
Place N queens on an N×N chessboard such that no two queens threaten each other. Return all
possible solutions.
Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]