Problem Solving Patterns
Frequency Counters
Uses objects to collect values or frequency of values. Sometimes allows the use of two or three loops (time complexity \(O(n))\) instead of nested loops (time complexity \(O(n ^ 2))\).
SAME: Write a function called same, which accepts two arrays. The function should return true if every value in the array has it’s corresponding value squared in the second array. The frequency of values must be the same.
ANAGRAM: Given two strings, write a function to determine if the second string is an anagram of the first. An anagram is a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.
Multiple Pointers
Creating pointers or values that correspond to an index or position and move towards the beginning, end or middle based on a certain condition. Very efficient for solving problems with minimal space complexity as well.
SUMZERO: Write a function called sumZero
which accepts a sorted array of integers.
The function should find the first pair where the sum is 0.
Return an array that includes both values that sum to zero or undefined if a pair does not exist.
COUNTUNIQVALS: Implement a function called countUniqVals
, which accepts a sorted array, and counts the unique values in the array.
There can be negative numbers in the array, but it will always be sorted.
Sliding Window
This pattern involves creating a window which can either be an array or number from one position to another. Depending on a certain condition, the window either increases or closes (and a new window is created). Very useful for keeping track of a subset of data in an array/string etc.
MAXSUBARRAYSUM: Write a function called maxSubarraySum
which accepts an array of integers and a number called n.
The function should calculate the maximum sum of n consecutive elements in the array.