#3006

Find Beautiful Indices in the Given Array I

Medium
Two PointersStringBinary SearchRolling HashString MatchingHash FunctionHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a single pass to find all occurrences of 'a' and 'b', storing their indices. This allows us to efficiently check the conditions for beauty without nested loops.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create two lists to store indices of occurrences for strings 'a' and 'b'.
  2. 2Step 2: Iterate through the string 's' once to fill these lists.
  3. 3Step 3: For each index in the list of 'a', check if there exists an index in the list of 'b' such that the absolute difference is less than or equal to 'k'.
  4. 4Step 4: If such a 'b' index exists, add the 'a' index to the result list.
solution.py12 lines
1def beautiful_indices(s, a, b, k):
2    result = []
3    len_a, len_b = len(a), len(b)
4    a_indices = [i for i in range(len(s) - len_a + 1) if s[i:i + len_a] == a]
5    b_indices = [j for j in range(len(s) - len_b + 1) if s[j:j + len_b] == b]
6    b_set = set(b_indices)
7    for i in a_indices:
8        for j in b_indices:
9            if abs(j - i) <= k:
10                result.append(i)
11                break
12    return sorted(set(result))

Complexity note: The time complexity is O(n) because we make a single pass to collect indices of 'a' and 'b', and then check conditions in linear time.

  • 1Using indices to track occurrences can significantly reduce the number of checks needed.
  • 2Sorting the result helps in returning the indices in the required order.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.