Array
Array Theory
An array is a collection of items stored at contiguous memory locations. The array elements can be accessed using an index. The index of the first element of the array is 0, the index of the second element is 1, and so on.
Experiment:
1 |
|
When we add or remove an element from an array, the elements are shifted accordingly. This is why adding or removing an element from an array is an O(n)
operation.
Binary Search
Given a ==sorted== array arr[]
of n
==distinct== elements, write a function to search a given element x
in arr[]
, return -1
if the element is not found.
pseudocode
1 |
|
Notice
l
andr
are the left and right indices of the array.- While condition is
l <= r
because whenl
is equal tor
we still need to check the element atl
orr
. - When calculating
(l+2)/2
we can get an overflow ifl
andr
are large. We can usel + (r-l)/2
instead to avoid overflow. - As we always set l or r to m+1 or m-1, the loop will eventually terminate.
Complexity
- Time complexity:
O(log n)
Implementation
1 |
|
Practice
- LeetCode 35 - Search Insert Position
- LeetCode 34 - Find First and Last Position of Element in Sorted Array
- LeetCode 69 - Sqrt(x)
- LeetCode 367 - Valid Perfect Square
Learned from practice
- Trick:
m * n < x
is equivlent tom < x / n
. This will avoid overflow but we need to be careful withn = 0
.
Double Pointer
Given an array and a value, remove all occurrences of that value from the array and return the new length of the array. The elements after the new length do not need to be considered.
idea
Keep two pointers to update the array. Fast pointer iterate the array as normal, while slow pointer record the new array.
Implementation
1 |
|
Practice
- LeetCode 26 - Remove Duplicates from Sorted Array
- LeetCode 283 - Move Zeroes
- LeetCode 844 - Backspace String Compare
- LeetCode 977 - Squares of a Sorted Array
Sliding Window
Given an array with n
elements and a value s
, you need to return the shortest subarray whose sum is greater or equal to s
.
Idea
Sliding window is a essentially updating the start and end position of a subarray until getting the expected result. Usually, the update is done in one iteration and we loop the index of the last position.
Implementation
1 |
|
Practice
Simulation
idea
When writing simulation programs, we often define complex loops. For these complex loops, it is important to remember that the rules followed by each loop remain unchanged. Additionally, it is a good approach to extract the functionality that can be reused from the complex program.
Practice
K Sum
Find K
distinct values in a given array that add up to a target value.
idea
Sort the array first, then use a brute force loop to iterate over the K-2
values. Use double pointers to search for the last two values in O(N)
complexity. The total complexity will be $O(N^{K-1})$.
The idea behind using double pointers to search for two values in a sorted array is as follows:
1 | ptr1 = left_bound; ptr2 = right_bound; |