Report
Report
Insertion Sort
Pair-wise swaps to insert new element to maintain sorted order
Two pointers – one for new element and one for where to swap it
O(n) for each swap and compare (one step)
O(n2) for reverse sorted array
Compares can be sometimes more expensive than swaps – use binary search in A[0 – i-1]
which is already sorted. O(log i)
Overall O(n log n) for compares instead of O(n2)
Requires insertion at right positions which may require shifting things to the right
Merge Sort
Recursive algo using merge
Divide and conquer split arrays
O(n log n)
T(n) = c1 + 2T(n/2) + cn
N leaf nodes and log n +1 levels
When the question asks for maximum/minimum and the constraints are large (ie., ~10^5),
there is a probability of binary search.
Kadane’s algorithm
basic idea is if adding the current element to the sum makes the sum negative, we need to
discard it and start a new subarray from the next element.
Parantheses
Faced problems with single length input as the stack would be empty and there is nothing to
compare or pop from the stack. Added simple stack empty checks to work around it.
Two Sum
Using hashmap we can keep target-current element and current element. If any future
element exists as the key in the map, we can easily return the value of the key and the
current element.
Similar approach can be used for Three sum.
Binary Addition
Ignoring the constraints, we can easily convert each of the inputs into integers, then add
them and then convert them back to binary string. But, due to the length of the inputs, the
integers will not fit in 64-bit space. We actually need to perform binary addition, bit-by-bit,
tracking carry and for each addition.
Learnt binary addition for solving this question.
Remove Element
Ignoring the in-place constraint, we can make a separate array.
Otherwise, we need to maintain a pointer for insert position and skip over the target values.
Since, order of the result array does not matter, swapping, even though it changes order of
elements, it does not create an issue.