Divisible Sum Pairs

  • + 0 comments

    Typescript solution: I have made the algorithm to run o(n) operation using the hash map, and much better compared to o(n^2) if we use brut force method such as nested for loop.

    function divisibleSumPairs(n: number, k: number, ar: number[]): number {
      // Write your code here
      const freq: { [key: number]: number } = {};
      let count = 0;
      ar.forEach((int) => {
        const remainder = int % k;
        const complement = (k - remainder) % k;
        if (complement in freq) {
          count += freq[complement];
        }
        if (remainder in freq) {
          freq[remainder]++;
        } else {
          freq[remainder] = 1;
        }
      });
      return count;
    }