Problem Solving Patterns

Problem Solving Patterns

Frequency Counters -> USE OBJECTS!!

to avoid O(n^2)

example 1

ex) same([1,2,3)], [4,1,9]) // true

same([1,2,3],[1,9]) // false

same([1,2,1],[4,4,1]) // false

function same(arr1, arr2) {
    if(arr1.length !== arr2.length) {
        return false;
    }
    let frequencyCounter1 = {}
    let frequencyCounter2 = {}
    for(let val of arr1) {
        frequencyCounter[val] = (frequencyCounter2[val] || 0) +1
    }
    for(let key in frequencyCounter1) {
        if(!(key ** 2 in frequencyCounter2)) {
            return false
        }
        if(frequencyCounter2[key**2] !== frequencyCounter1[key] {
            return false
        }
    }
    return true
    }

Time Complexity - O(n)


example 2

anagram

function validAnagram(first, second) {
    if(first.length !== second.length) {
        return false;
    }

    const lookup = {};

    for (let i = 0; i<first.length; i++) {
        let letter = first[i];
        lookup[letter] ? lookup[letter] += 1 : lookup[letter] =1;
    }

    for (let i=0; i<second.length;i++) {
        let letter = second[i];
        if (!lookup[letter]) {
            return false;
        } else {
            lookup[letter] -= 1;
        }
    }
    return true;
}

// { a:0, n:0, g:0, r:0, m:0 }
validAnagram('anagrams', 'nagaramm')

example 3

sameFrequency

(182, 281) // true

(34, 14) // false

(22, 222) // false

function sameFrequency(num1, num2) {
    let strNum1 = num1.toString();
    let strNum2 = num2.toString();
    if(strNum1.length !== strNum2.length) return false;

    let countNum1 = {};
    let countNum2 = {};

    for(let i = 0; i < strNum1.length; i++) {
        countNum1[strNum1[i] = (countNum1[strNum1[i]] || 0) +1
    }

    for(let j = 0; j < strNum1.length; j++) {
        countNum2[strNum2[j] = (countNum2[strNum2[j]] || 0) +1
    }

    for(let key in countNum1) {
        if(countNum1[key] !== countNum2[key]) return false;
    }

    return true;
}