Similar Problems

Similar Problems not available

Number Of Ways To Select Buildings - Leetcode Solution


  • amazon

LeetCode:  Number Of Ways To Select Buildings Leetcode Solution

Difficulty: Medium

Topics: string dynamic-programming prefix-sum  

The problem "Number Of Ways To Select Buildings" on LeetCode is a bit tricky but can be easily solved by using a simple formula. Here, we have to find the number of ways to select two buildings such that the maximum height difference between them is at most a given integer k.

We can solve this problem by using a two-pointer approach. We can sort the buildings' height and then use two pointers, and iterate through the sorted building height array, such that the left pointer starts from the beginning of the array, and the right pointer starts from i+1 position (i=0 to N-1). We can then keep moving the pointers and updating the count of the valid pairs of buildings.

Here is the step-by-step solution to the problem:

  1. Sort the array of building heights.

  2. Initialize two pointers, left and right, to point to the first and second elements of the array, respectively.

  3. Initialize a variable, count, to zero.

  4. While the right pointer is less than the size of the array:

    a. If the absolute difference between the heights of the buildings at the left and right pointers is less than or equal to k, increment the count and move the right pointer to the next element.

    b. If not, move the left pointer to the next element.

  5. Return the count.

The time complexity of this algorithm is O(nlogn) due to the sorting of the array. The space complexity is O(1) as we are not using any extra space.

Here is the Python code to implement the above algorithm:

def numWays(buildings, k):
    count = 0
    left = 0
    for right in range(1, len(buildings)):
        while left < right and buildings[right] - buildings[left] > k:
            left += 1
        count += (right - left)
    return count % (10**9 + 7)

In this code, we first sort the buildings list and initialize the count variable to zero. We then iterate through the buildings' list using the right pointer and check the difference between the buildings' heights at the left and right pointers. If the difference is greater than k, we increment the left pointer; otherwise, we count all the valid pairs of buildings by adding (right - left) to the count. Finally, we return the count modulo (10**9 + 7) as it is mentioned in the problem constraints.

Number Of Ways To Select Buildings Solution Code