Categories
Array Leetcode Loop Sort

Most Visited Website Pattern

let mostVisitedPattern = function(username, timestamp, website) {
    let map = new Map();
    for (let i = 0; i < username.length; i++) {
        if (map.has(username[i])) {
            map.get(username[i]).push([website[i], timestamp[i]]);
        }
        else {
            map.set(username[i], [[website[i], timestamp[i]]]);
        }
    }

    // get all possibilites
    let visitedPattern = {};
    let possibilityMap = new Map();
    for(let [user, visits] of map.entries()) {
        visitedPattern[user] = {};
        const value = visits.sort((a, b) => a[1] - b[1]).map(([a]) => a);

        if ( value.length < 3) continue;
        for (let i = 0; i < value.length - 2; i++) {
            for (let j = i + 1; j < value.length - 1; j++) {
                for (let k = j + 1; k < value.length; k++) {
                    let key = `${value[i]},${value[j]},${value[k]}`;
                    if(possibilityMap.has(key)) {
                        if(!visitedPattern[user][key]) {
                            possibilityMap.set(key, possibilityMap.get(key) + 1);
                            visitedPattern[user][key] = 1;
                        }
                    }
                    else {
                        possibilityMap.set(key, 1);
                        visitedPattern[user][key] = 1;
                    }
                }
            }
        }
    }

    const result = [...possibilityMap];
    return result.sort((a, b) => {
        if(a[1] < b[1]) {
            return 1;
        }
        else if (a[1] > b[1]) {
            return -1;
        }
        return a[0].localeCompare(b[0]);
    }).map(arr => arr[0]).shift().split(','); //?


    // result.pop(); //?
        // .map(arr => arr[0]).pop().split('|'); //?
};
Categories
Array Leetcode Sort

Search Suggestion System (Simple)

let suggestedProducts = function(products, searchWord) {
products.sort();

let result = [];
for(let i = 0; i < searchWord.length; i++) {
products = products.filter(p => p[i] === searchWord[i]);
result.push(products.slice(0, Math.min(3, products.length)));
}

return result; //?
};
Categories
Recursion Sort

Merge Sort

let mergeSort = function(numbers) {

    function mergeSort(arr) {
        if (arr.length === 1) return arr;
        let center = Math.floor(arr.length / 2);
        let left = arr.slice(0, center);
        let right = arr.slice(center);
        return merge(mergeSort(left), mergeSort(right));
    }
    
    function merge(left, right) {
        let results = [];
        while (left.length && right.length) {
            if (left[0] < right[0]) {
                results.push(left.shift());
            }
            else {
                results.push(right.shift());
            }
        }

        return [...results, ...left, ...right];
    }

    return mergeSort(numbers);
}