Algo go to Flashcards

1
Q

https://leetcode.com/problems/valid-parentheses/

A

Make a dict with bracket_ref = {“}”:”{“, “]”:”[”, “)”:”(“}
create empty stack
Iterate in str, check if char is not in bracket_ref then append in stack

Else,
check if stack is not empty and char == stack[-1], then continue
else, return False

At the end check if stack is not empty return False, else return True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

https://leetcode.com/problems/merge-two-sorted-lists

A

create new node head and curr is same as head. if compare list1 and list2 val and do curr.next whichever is less. then update that list node to next and curr also next. At end return head.next

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

A

1) single transaction, Keep in mind that max should come after min, whenever min is updated also update max. Whenver min is update make max = -1

2) multiple transactions, run while loop till u find min number and while loop till max num , find difference and keep track of max diff and keep updating min and max variables in outer while loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

https://leetcode.com/problems/invert-binary-tree/

A

if root is None:
return None

    root.left, root.right = root.right, root.left
    self.invertTree(root.left)
    self.invertTree(root.right)
    return root
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Binary search

A

l = 0
r = len(nums)-1

    while l <= r:
        mid = (l+r)//2
        if target == nums[mid]:
            return mid
        if target < nums[mid]:
            r = mid-1
        else:
            l = mid+1

    return -1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

https://leetcode.com/problems/maximum-subarray/

A

curr_sum = nums[0]
max_till_now = nums[0]

    for i in range(1, len(nums)):
        curr_sum += nums[i]
        curr_sum = max(curr_sum, nums[i])
        max_till_now = max(max_till_now, curr_sum)
        
    return max_till_now
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

https://leetcode.com/problems/insert-interval/description/

You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.

Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).

Return intervals after the insertion.

Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

A

create empty result list
iterate over input list
check if current element end is less than newInterval start, that means element will
come into the result list.

if current element start is more than newInterval  end, that means newinterval is 
 smaller and will come into result list. But update the newInterval  variable with 
current element, bcz that is not appended till now.

otherwise, we know there is an overlap, so newInterval start becomes minimum    of newInterval start or current element, similarly, end becomes max of the 2.

Continue

at the end remember to append newInterval

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Print level order traversal line by line

A

Do it like normal level order traversal, just add Null after pushing root in the queue.
And while iteration check if Null comes then pop the Null and add Null again in the queue (so that null is added after every level)

OR

Take the length of queue and iterate it that times only.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Zig zag Level order traversal

A

Take 2 stacks.
add root in S1.
Run while loop on S1 or S2:
check if S1 is not empty, then pop and print and add in S2, first left and then right.

Check if s2 is not empty, then pop and add in S1, first right and then left.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/

A

2 scenarios:
1) if both keys are present mentioned in ques

recursively go to left and right and check if root.key == n1 or root.key == n2, if yes in that case return the root.
After recursion check if left_lca and right_lca both present return root (it will happen when both are in different subtree)
Otherwise return which ever is present( it will happen when one lca is present in same subtree of other lca

2) It is not mandatory that both keys are present
Take a list v =[False, False]
do same as above but also update v list value, if n1 is present v[0] = True, if n2 is present v[1] = True
Now check if v[0] and v[1] are true then return root (case of lca in diff subtrees)

if only v[0] is true, find n2 in its subtree find(left_lca, n2) – left_lca is considered as root
same if only v[1] is true, find n1 in its subtree find(right_lca, n1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Maximum subarray
https://leetcode.com/problems/maximum-subarray/submissions/919244531/

A

Take 2 variables curr_sum and curr_max save zero index value in both, start from index one and iterate take current index item and add in curr_sum.
Check if current item is larger than curr_sum then curr_sum = current item otherwise the curr_sum = added part.

for curr_max, check if curr_max is greater or curr_sum

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

01 Matrix

Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

https://leetcode.com/problems/01-matrix/description/

A

Bcz we have to find nearest cell we will do BFS and not DFS.

Replace all 1s with MAX_VALUE

take a queue and append all the row,col which contains 0, as we have to find the nearest path.

Now we will iterate the queue like we do in BFS and pop the elements from queue and check in all 4 directions if the value of current cell after adding direction is greater than source cell+1. if yes, replace current cell value with source cell+1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

https://leetcode.com/problems/balanced-binary-tree/description/

Check if tree is height balanced or not

A

At each point do recursive call and check if left height minus right height is greater than 1 then return -1 otherwise calculate max(lh,rh)+1 and return

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Merge K sorted arrays (not list)

A

Take min heap and insert -

for i, item in enumerate(arr):
heappush(min_heap,[item[0], i, 0])
keep popping the top of heap and merge in new array and check if the next index of that array exists then insert the next element.

code:

from heapq import heapify, heappush, heappop

def merge_sorted_arrays(arr,k):
min_heap = []
merged_array = []

for i, item in enumerate(arr):
    heappush(min_heap,[item[0], i, 0])

while min_heap:
    elem = heappop(min_heap)
    merged_array.append(elem[0])
    
    if len(arr[elem[1]]) > elem[2]+1:
        heappush(min_heap,[arr[elem[1]][elem[2]+1], elem[1], elem[2]+1])
        
print("res:", merged_array)

arr = [[2, 6, 12, 34], [1, 9, 20, 1000], [23, 34, 90, 2000]]
merge_sorted_arrays(arr, len(arr))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Find median of stream of numbers

https://www.geeksforgeeks.org/median-of-stream-of-integers-running-integers/

A

We have to maintain two heaps min_heap for maximum side and max_heap for minimum side. so that the top of both heaps can give in median.

Either both heaps can contain equal number of items or max_heap(smaller side) will contain one extra item.

Push in max_heap and pop and push back in min_heap. check length if greater side heap has more elements pop and push back.

check if lengths are different that means there are odd number of elements then print max_heap[0]
else
add and divide by 2 both heaps top

from heapq import heappush, heappop

def find_median(arr, n):
large = []
small = []

for item in arr:
    heappush(small, -item)
    heappush(large, -heappop(small))
    
    if len(large) > len(small):
        heappush(small, -heappop(large))
    
    if len(large) != len(small):
        print(-small[0])
    else:
        print((small[0]+large[0])/2)

if __name__ == ‘__main__’:
arr = [5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4]
n = len(arr)
find_median(arr, n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Longest substring without repeating character

https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

A

Take a set and keep on adding unique chars in set. When repeating char comes keep on removing the char from left till the point of repeating char.

the trick is not to remove the specific repeating char and insert it again. Just remove chars before the repeating char and update left.

17
Q

3sum - find 0 for a triplet sum

https://leetcode.com/problems/3sum/description/

A

Sort array.
We use two pointer approach by fixing one index i.e i. Then L = i+1 and R = len-1.
Increment L if sum is smaller, decrement R if sum is greater, if sum is equal append in list.

To check duplicacy there will be 2 checks. One, at starting while fixing the index that nums[i] != nums[i-1].

Other, when we found triplet increment L till same number and decrement R till same num (array is sorted)

18
Q

Longest Palindromic substring

https://leetcode.com/problems/longest-palindromic-substring/description/

A

Substring can be odd length or even length. For odd length start from a point considered as centre and use 2 pointer approach, one goes to left and other goes to right. Take the difference in right and left.

For even start from i and i-1 and got to left and right

19
Q

Clone a graph

https://leetcode.com/problems/clone-graph/description/

A

BFS in graph using queue.

Use a hashmap/dictionary to keep on saving the node visited and its value.

iterate through front at queue node’s neighbour and check if already visited or not. If not add in the queue and dictionary.

In last add the current neighbor in front node’s neighbor list

20
Q

Delete nth node from last
https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

A

take 2 variables- first and second

iterate till n and see if second becomes None, it can happen if n > len of linkedList or we have to delete the head. check if i == n-1 that means we have remove head, do head = head.next.

after the for loop ,run while loop to take second to end and first to prev node that is to delete and change the pointer.

21
Q

Evaluate reverse polish notation https://leetcode.com/problems/evaluate-reverse-polish-notation/description/

A

Create dict of operators and their actions using lambda function.
Use stack, keep on adding if the item is not in dict of operator, else pop last 2 num and apply the lambda function on those 2 nums and push in stack.