EECS 281 Data Structures and Algorithms
EECS 281 Data Structures and Algorithms
Master Theorem
Then:
Recursion
| Recurrence | Example | Big-O Solution |
|---|---|---|
| Binary Search | ||
| Linear Search | ||
| Tree Traversal | ||
| Selection/etc. Sorts | ||
| Merge/Quick Sorts |
2D Table Search
Improved Binary Partition Search
- On the middle column, perform a binary search to find the row that contains the target value.
- If the target value is found, return true.
- If the target value is not found, recursively search the bottom-left and top-right submatrices.
Stepwise Linear Search
time complexity
- Start at the top-right corner of the table.
- If the current value is equal to the target, return true.
- If the current value is greater than the target, move left.
- If the current value is less than the target, move down.
Majority Element
A majority element in an array is an element that appears more than times, where is the size of the array.
Boyer-Moore Voting Algorithm
time, space
- Initialize a candidate element and a count.
- Iterate through the array:
- If the count is zero, set the current element as the candidate and set count to 1.
- If the current element is equal to the candidate, increment the count.
- If the current element is not equal to the candidate, decrement the count.
- After the iteration, the candidate is the majority element if it exists. (Iterate again to confirm if the candidate is indeed the majority element.)
int findMajorityElement(vector<int>& nums) {
int candidate = 0, count = 0;
for (int num : nums) {
if (count == 0) candidate = num, count = 1;
else if (num == candidate) count++;
else count--;
}
// Verify if the candidate is indeed the majority element
count = 0;
for (int num : nums)
if (num == candidate)
count++;
return (count > nums.size() / 2) ? candidate : -1; // Return -1 if no majority element exists
}
Divide and Conquer Approach
time, space
- Divide the array into two halves.
- Recursively find the majority element in each half.
- If both halves return the same majority element, that is the majority element for the entire array.
- If they return different elements, count the occurrences of each in the entire array and return the one that appears more than n/2 times, if any.
Misra-Gries Algorithm
To find elements that appear more than times in an array.
time, space
- Initialize a map to store up to k-1 candidate elements and their counts.
- Iterate through the array:
- If the current element is in the map, increment its count.
- If the current element is not in the map and the map has less than k-1 elements, add the current element to the map with a count of 1.
- If the current element is not in the map and the map has k-1 elements, decrement the count of each element in the map. Remove any elements whose count drops to zero.
- After processing the array, the map contains potential candidates. Verify each candidate by counting its occurrences in the original array.