Problems
Anagrams (ABC, CBA are anagrams of each other)
- Can sort both array and compare both
- Can count all characters of string1 and decrement count by second string2. Check if all values are 0. Use dictionary, defaultdict.
Array Pair Sum
Problem - Given an integer array, output all the unique pairs that sum up to a specific value k
Solution - The O(N) algorithm uses the set data structure. We perform a linear pass from the beginning and for each element we check whether k-element is in the set of seen numbers. If it is, then we found a pair of sum k and add it to the output. If not, this element doesn't belong to a pair yet, and we add it to the set of seen elements
Find the Missing Element
Problem - Consider an array of non-negative integers. A second array is formed by shuffling the elements of the first array and deleting a random element. Given these two arrays, find which element is missing in the second array
Solution - O(N) - We can use a hashtable and store the number of times each element appears in the second array. Then for each element in the first array we decrement its counter. Once hit an element with zero count that's the missing element
we can achieve linear time and constant space complexity without any problems. Here it is: initialize a variable to 0, thenXOR every element in the first and second arrays with that variable. In the end, the value of the variable is the result, missing element in array2.
Largest Continuous Sum
Problem - Given an array of integers (positive and negative) find the largest continuous sum
Solution - O(N) - Use current_sum and max_sum to track the values and update the values using current_sum = max(current_sum + num, num) and max_sum(current_sum, max_sum)
Sentence Reversal
Problem - Given a string of words, reverse all the words
Solution - Use stack to push the words and then print the stack