Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Count the Number of Fair Pairs

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2563" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given a 0-indexed integer array nums of size n and two integers lower and upper, return the number of fair pairs. A pair (i, j) is fair if: 0 <= i < j < n, and lower <= nums[i] + nums[j] <= upper Example 1: Input: nums = [0,1,7,4,4,5], lower = 3, upper = 6 Output: 6 Explanation: There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5). Example 2: Input: nums = [1,7,9,2,5], lower = 11, upper = 11 Output: 1 Explanation: There is a single fair pair: (2,3). Constraints: 1 <= nums.length <= 105 nums.length == n -109 <= nums[i] <= 109 -109 <= lower <= upper <= 109

Explanation

Here's a solution to the problem, focusing on efficiency and optimality:

  • Sorting: Sort the input array nums. This enables us to use binary search effectively to find the range of elements that satisfy the lower <= nums[i] + nums[j] <= upper condition for each nums[i].
  • Binary Search: Iterate through the sorted array. For each nums[i], use binary search to find the first element nums[j] (where j > i) such that nums[i] + nums[j] >= lower and the last element nums[k] such that nums[i] + nums[k] <= upper. The number of fair pairs for nums[i] is then k - j + 1.

  • Time Complexity: O(n log n) due to sorting and binary search. Space Complexity: O(1) if sorting is done in-place. O(n) otherwise (depending on the sorting algorithm).

Code

    def countFairPairs(nums, lower, upper):
    nums.sort()
    n = len(nums)
    count = 0

    for i in range(n):
        left = i + 1
        right = n - 1
        start_index = -1

        while left <= right:
            mid = (left + right) // 2
            if nums[i] + nums[mid] >= lower:
                start_index = mid
                right = mid - 1
            else:
                left = mid + 1

        left = i + 1
        right = n - 1
        end_index = -1

        while left <= right:
            mid = (left + right) // 2
            if nums[i] + nums[mid] <= upper:
                end_index = mid
                left = mid + 1
            else:
                right = mid - 1

        if start_index != -1 and end_index != -1 and start_index <= end_index:
            count += (end_index - start_index + 1)

    return count

More from this blog

C

Chatmagic blog

2894 posts