DEV Community

David
David

Posted on

How I Solved the HackerRank "Picking Numbers" Problem in TypeScript

I recently tackled the "Picking Numbers" problem, a fun challenge where we need to find the longest subarray where the absolute difference between any two elements is less than or equal to 1. Here's how I solved this problem using TypeScript.

Problem Breakdown
Given an array of integers, the task is to:

  1. Find the subarray where the absolute difference between any two elements is less than or equal to 1.

  2. Return the length of the longest such subarray.

Approach
The problem boils down to finding subarrays that only contain two adjacent values, like numbers x and x + 1. For instance, if you have an array [1, 2, 2, 3], both [1, 2, 2] and [2, 2, 3] are valid subarrays since the difference between any two elements in these subarrays is at most 1.

To solve this, I took the following steps:

  • Count the frequency of each number in the array.

  • Check consecutive pairs of numbers and calculate their total frequency, which represents the length of the longest subarray for those two numbers.

  • Track the maximum length of the valid subarrays across all possible pairs of consecutive numbers.

TypeScript Solution
Here’s the solution I came up with:

function pickingNumbers(a: number[]): number {
    let frequency = new Array(100).fill(0);

    // Step 1: Count the frequency of each element in the array
    for (let i = 0; i < a.length; i++) {
        frequency[a[i]]++;
    }

    let maxLength = 0;

    // Step 2: Check pairs of consecutive numbers (x and x+1)
    for (let i = 1; i < frequency.length; i++) {
        maxLength = Math.max(maxLength, frequency[i] + frequency[i - 1]);
    }

    return maxLength;
}
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Explanation

  • Initialize Frequency Array:
    I used an array frequencywith 100 elements, initialized to zero. Since the problem guarantees that the integers in the array are between 1 and 100, this array allows us to count the occurrences of each number efficiently.

  • Count Frequencies:
    For each element in the input array a, we increment the corresponding index in the frequencyarray. For example, if a[i] = 5, we increase frequency[5] by 1. This will give us the number of occurrences of each number in the array.

  • Check Consecutive Numbers:
    Once we have the frequency counts, we need to find the longest subarray where the absolute difference between any two numbers is less than or equal to 1. This can be done by adding the frequency of each number i and the frequency of its neighbor i-1 (i.e., frequency[i] + frequency[i-1]).

  • Track the Maximum Length:
    As we loop through the frequency array, we keep updating the maxLength with the largest value found for consecutive numbers. This gives us the length of the longest valid subarray.

Top comments (0)