Minimum Absolute Difference and Related Problems

Given a array of distinct integers, find all pairs with the smallest absolute difference and return them in ascending order.


function findMinAbsDifference(arr) {
    let result = [];
    arr.sort((a, b) => a - b);
    let minDiff = Infinity;
    for (let i = 0; i < arr.length - 1; i++) {
        let diff = arr[i + 1] - arr[i];
        if (diff < minDiff) {
            minDiff = diff;
            result = [];
        }
        if (diff === minDiff) {
            result.push([arr[i], arr[i + 1]]);
        }
    }
    return result;
}

Find the nth number that is divisible by a, b, or c.


function findNthUglyNumber(n, a, b, c) {
    function gcd(x, y) {
        if (y === 0) return x;
        return gcd(y, x % y);
    }
    let low = 0, high = 2 * Math.pow(10, 9);
    while (low + 1 < high) {
        let mid = Math.floor((low + high) / 2);
        let count = Math.floor(mid / a) + Math.floor(mid / b) + Math.floor(mid / c);
        count -= Math.floor(mid / lcm(a, b)) + Math.floor(mid / lcm(a, c)) + Math.floor(mid / lcm(b, c));
        count += Math.floor(mid / lcm(lcm(a, b), c));
        if (count < n) {
            low = mid;
        } else {
            high = mid;
        }
    }
    return high;

    function lcm(x, y) {
        return (x * y) / gcd(x, y);
    }
}

Determine the minimum cost to move chips to the same position on a number line.


function minCostToMoveChips(chips) {
    let evenCount = 0, oddCount = 0;
    chips.forEach(chip => {
        if (chip % 2 === 0) {
            evenCount++;
        } else {
            oddCount++;
        }
    });
    return Math.min(evenCount, oddCount);
}

Find all pairs (x, y) that satisfy a given function f(x, y) = z.


function findFunctionSolutions(customFunction, z) {
    let solutions = [];
    for (let x = 1; x <= 1000; x++) {
        for (let y = 1; y <= 1000; y++) {
            if (customFunction.f(x, y) === z) {
                solutions.push([x, y]);
            }
        }
    }
    return solutions;
}

Generate a circular permutation staritng from a given value.


function generateCircularPermutation(n, start) {
    let size = Math.pow(2, n);
    let result = [start];
    let visited = new Array(size).fill(false);
    visited[start] = true;
    for (let i = 1; i < size; i++) {
        let next = result[i - 1];
        for (let j = 0; j < n; j++) {
            let candidate = next ^ (1 << j);
            if (!visited[candidate]) {
                result.push(candidate);
                visited[candidate] = true;
                break;
            }
        }
    }
    return result;
}

Calculate the minimum length of a substring to replace to balance a string.


function minSubstringToBalance(s) {
    let count = { Q: 0, W: 0, E: 0, R: 0 };
    let target = s.length / 4;
    for (let char of s) {
        count[char]++;
    }
    let left = 0, right = 0, minLen = s.length;
    while (right < s.length) {
        count[s[right]]--;
        right++;
        while (Object.values(count).every(val => val <= target)) {
            minLen = Math.min(minLen, right - left);
            count[s[left]]++;
            left++;
        }
    }
    return minLen;
}

Determine the minimum swaps needed too make two strings equal.


function minSwapsToEqualStrings(s1, s2) {
    let mismatchX = 0, mismatchY = 0;
    for (let i = 0; i < s1.length; i++) {
        if (s1[i] !== s2[i]) {
            if (s1[i] === 'x') {
                mismatchX++;
            } else {
                mismatchY++;
            }
        }
    }
    if ((mismatchX + mismatchY) % 2 !== 0) return -1;
    return Math.floor(mismatchX / 2) + Math.floor(mismatchY / 2) + (mismatchX % 2);
}

Count the number of subarrays with exactly k odd numbers.


function countSubarraysWithKOddNumbers(nums, k) {
    let oddIndices = [-1];
    let count = 0;
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] % 2 === 1) {
            oddIndices.push(i);
        }
        if (oddIndices.length > k + 1) {
            count += (oddIndices[oddIndices.length - 1] - oddIndices[oddIndices.length - 2]) *
                     (oddIndices[oddIndices.length - 1 - k] - oddIndices[oddIndices.length - 2 - k]);
        }
    }
    if (oddIndices.length > k) {
        count += (nums.length - oddIndices[oddIndices.length - 1]) *
                 (oddIndices[oddIndices.length - k] - oddIndices[oddIndices.length - 1 - k]);
    }
    return count;
}

Calculate the number of odd cells in a matrix after specified row and column increments.


function countOddCells(n, m, indices) {
    let rows = new Array(n).fill(0);
    let cols = new Array(m).fill(0);
    for (let [r, c] of indices) {
        rows[r]++;
        cols[c]++;
    }
    let oddCount = 0;
    for (let r = 0; r < n; r++) {
        for (let c = 0; c < m; c++) {
            if ((rows[r] + cols[c]) % 2 === 1) {
                oddCount++;
            }
        }
    }
    return oddCount;
}

Tags: javascript algorithms Arrays math strings

Posted on Thu, 21 May 2026 21:02:42 +0000 by philhale