Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Online Majority Element In Subarray

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1157" 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

Design a data structure that efficiently finds the majority element of a given subarray. The majority element of a subarray is an element that occurs threshold times or more in the subarray. Implementing the MajorityChecker class: MajorityChecker(int[] arr) Initializes the instance of the class with the given array arr. int query(int left, int right, int threshold) returns the element in the subarray arr[left...right] that occurs at least threshold times, or -1 if no such element exists. Example 1: Input ["MajorityChecker", "query", "query", "query"] [[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]] Output [null, 1, -1, 2] Explanation MajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]); majorityChecker.query(0, 5, 4); // return 1 majorityChecker.query(0, 3, 3); // return -1 majorityChecker.query(2, 3, 2); // return 2 Constraints: 1 <= arr.length <= 2 104 1 <= arr[i] <= 2 104 0 <= left <= right < arr.length threshold <= right - left + 1 2 * threshold > right - left + 1 At most 104 calls will be made to query.

Explanation

Here's a breakdown of the approach, complexities, and the Python code for an efficient MajorityChecker data structure:

  • Preprocessing with Index Lists: Build a dictionary where keys are the unique elements in the input array and values are sorted lists of their indices in the array. This enables efficient binary search for counting occurrences within a given range.

  • Randomized Candidate Selection: In the query function, randomly sample elements from the subarray. For each candidate, use binary search on the precomputed index lists to count its occurrences within the subarray range.

  • Threshold Check: If a candidate's count meets or exceeds the given threshold, return that element. After a reasonable number of trials (e.g., based on desired probability of success), if no majority element is found, return -1.

  • Complexity: O(NlogN) preprocessing time and O(N) space, O(KlogN) query time where K is the number of trials and N is the length of array.

Code

    import random
from collections import defaultdict

class MajorityChecker:
    def __init__(self, arr):
        self.arr = arr
        self.indices = defaultdict(list)
        for i, num in enumerate(arr):
            self.indices[num].append(i)

    def query(self, left, right, threshold):
        for _ in range(10):  # Number of trials (adjust as needed)
            idx = random.randint(left, right)
            candidate = self.arr[idx]

            count = self.count_occurrences(candidate, left, right)
            if count >= threshold:
                return candidate
        return -1

    def count_occurrences(self, num, left, right):
        indices = self.indices[num]

        # Binary search for the first index >= left
        l, r = 0, len(indices) - 1
        first = -1
        while l <= r:
            mid = (l + r) // 2
            if indices[mid] >= left:
                first = mid
                r = mid - 1
            else:
                l = mid + 1

        # Binary search for the last index <= right
        l, r = 0, len(indices) - 1
        last = -1
        while l <= r:
            mid = (l + r) // 2
            if indices[mid] <= right:
                last = mid
                l = mid + 1
            else:
                r = mid - 1

        if first == -1 or last == -1:
            return 0

        return last - first + 1

More from this blog

C

Chatmagic blog

2894 posts