Problem Approach Flashcards
Trapping water
Have two separate arrays for figuring out the maximum heights when you start from the left and if you start from the right.
Now when you iterate through the given array you can find the minimum among the left and right max arrays, say that is X.
X - value of the current index in the given array will give you its capacity.
Add up all the values and thats how many units of water
How do you reverse a string? [sort of a linkedlist o(1) space problem]
Can be done with two pointers at the end and exchange as you iterate
What is the best approach when there are repetitive actions to be done with just a change of parameters?
For instance, to swap adjacent nodes in a linkedList
When there are repetitive actions to be done with just a change of parameters recursion is a good choice
swapNodes(Node s) { // since we are passing the node next to the second first.next = swapNode(second.next); second.next = first;
// in the end return the second return second; }
How do you reverse a linked list
Recursion can be used since only a change of parameters needs to be done with each call.
Capacity of water
Since the capacity is determined by both width and height, we can start with the largest width and work our way.
so therefore start with the extremes and calculate the capacity and move either pointer only if there is a line greater than it(this means that there is a possibility of higher capacity). At every point you will keep track of the max capacity
Three sum problem
a+b+c =0 given a list of integers
sort the array(nlogn)
then taking one of the elements as a pivot we call twosum method
In this method we calculate the sum of pivot + lo + high
if that sum is > 0 then we need to decrement high
if sum < 0 increment lo
else we have our result
now to avoid having duplicates we can move our lo pointer if two values are repeated (i.e duplicates)
give an array of integers find the product of i = product of values at all other indexes than i
generate two new arrays left and right.
Left array is the product of all elements to the left of an index
Right array is the product of all elements to the right of an index
then multiple the values in both arrays to get the result
Find the median of two sorted arrays
this is like the last step of merge in merge sort. you compare the first elements and add to an auxiliary array . This would take O(m+n)
In order to do this in O(log(m+n)) you can just consider only the left array of the combined array(so only half of the subset) since all elements to the left of median will be less than median.
consider what is the mid point for the combined array that gives number of elements x in left array
Now assuming all x come from the first array. we start from the middle of the first array and compare that value with the mid+1 of the second array. If its more that indicates that we need to consider more elements from the second array. Similar comparison is done for the second array as well. if neither conditions satisfy then we have found the right partition and just need to confirm by comparing both mid’s
Dutch national flag problem. Sort a given array of integers in order where each color represents a number. This must be done in place and going over the array only once
[0,1,0,2]
We use three pointers
one is the current element (curr)
one is the leftmost element ( left)
one is the rightmost element (right)
if the current == 0 we swap curr with left
then we curr++ and left++
if the current == 2 we swap curr with right
then right–;
else we curr++;
all of this is done till curr <= right;
Quick Select
Used in problems where kth frequent, kth largest, kth less frequent
similar to doing quick sort but we can make it more effective by considering only one half
while partitioning consider right most element as pivot
pivot = arr[right]
i= left;
j = left till right
compare if the j <= pivot then swap i with j
once you go through all elements then swap i with pivot and return i;
Then compare i with the kth element position. If it isn’t same then consider which side of the array to perform quick select again
Given a graph, of street view with time to travel between vertices. Given a start and end location find the time taken to travel.
Similar to Dijakstra
What data structure would you use for a LRU Cache(least recently used) that will do insert and delete in constant time and delete the first added value?
There is a structure that combines both hashmap and linked list. in Java LinkedHashMap.
OR
you can use a hashmap of key to value(value: is a doubly linked list so that removal from front is easy)
How would you find the longest palindromic substring
an approach is to try expand as you go through the characters of the string. eventually you will reach a point where a possible palindrome can form as you expand from it
Some operations whose time complexity is often mistaken
- Adding or removing (or even changing) just one character anywhere in a string is O(n)O(n), because strings are immutable. The entire string is rebuilt for every change.
- Adding or removing not from the end of a list, vector, or array is O(n)O(n) because the other items are moved up to make a gap or down to fill in the gap.
- Checking if an item is in a list, because this requires a linear search. Even if you use binary search, it’ll still be O(\log n)
- Recall that checking if an item is in a set is O(1)
Coin change problem
Given coins [1,2,5] what is the minimum coins to make amount =11
Can use dynamic programming
generate a dp array starting from 0 to the amount.
initialize all values to amount+1;
initialize dp[0] = 0 , since in order to generate amount =0 the minimum coins will always be 0.
keep building this dp array utilizing the previous values
the dp[amount] will have the answer. if its value > amount+1 that means there is no solution
How would you return the next lexicographic permutation for a given array of integers
eg: [1,2,3]
the permutations are 123, 132,321 etc
ans: 132
start from the rightmost side and find the first number a[i] < a[i+1]
in this case it is 2
then start again from the right and find the first number > 2, which is 3.
exchange 2 and 3
1 3 2
and reverse all elements after 3
How do you group given strings into groups of anagrams?
Method 1:
for every string
sort the string
put it in a map with key(the sorted string) and value the actual string
this way the map with have a list of strings in its values
return a new ArrayList(map.values())
Method 2:
use an array of 26 letters for EACH string.
populate it with the count of characters in that word
example :raat will have [2,0…….1,…..1] where 2 is the count for ‘a’ and 1 for r and t
generate a unique key using these values(can add # before each count to generate a unique string to be used a hash key of a map or add all the counts )
check if that key exists in the map if it does append the string s to the list of values
else add it to the map
return a new ArrayList(map.values())
Parentheses problem
Stacks and recursion