Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Iterator for Combination

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1286" 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 the CombinationIterator class: CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments. next() Returns the next combination of length combinationLength in lexicographical order. hasNext() Returns true if and only if there exists a next combination. Example 1: Input ["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"] [["abc", 2], [], [], [], [], [], []] Output [null, "ab", true, "ac", true, "bc", false] Explanation CombinationIterator itr = new CombinationIterator("abc", 2); itr.next(); // return "ab" itr.hasNext(); // return True itr.next(); // return "ac" itr.hasNext(); // return True itr.next(); // return "bc" itr.hasNext(); // return False Constraints: 1 <= combinationLength <= characters.length <= 15 All the characters of characters are unique. At most 104 calls will be made to next and hasNext. It is guaranteed that all calls of the function next are valid.

Explanation

Here's an efficient solution to the CombinationIterator problem:

  • Precompute all combinations: Generate all possible combinations of the specified length from the given characters during initialization. Store these combinations in a list.
  • Maintain an index: Keep track of the current combination index. The next() method returns the combination at the current index, and the hasNext() method checks if the index is within the bounds of the list.

  • Runtime Complexity: O(C(n, k)) for initialization, O(1) for next() and hasNext(), where n is the length of the characters and k is the combinationLength. Storage Complexity: O(C(n, k)) to store all combinations.

Code

    from itertools import combinations

class CombinationIterator:

    def __init__(self, characters: str, combinationLength: int):
        self.combinations = list(map("".join, combinations(characters, combinationLength)))
        self.index = 0

    def next(self) -> str:
        result = self.combinations[self.index]
        self.index += 1
        return result

    def hasNext(self) -> bool:
        return self.index < len(self.combinations)

More from this blog

C

Chatmagic blog

2894 posts