Uber Interview - Senior Software Engineer - Nov 2024

Difficulty: MEDIUMCategory: DSAFrequency: 1Asked On 2025-04-01

Problem Statement

Write Code using sliding window with O(N^2) time and O(N^3) space complexity


Find All Substrings of Length K with Distinct Characters

Given a string s and an integer k, return all substrings of length k such that each substring has all distinct characters.

Use a sliding window approach to solve the problem with O(N²) time complexity and O(N³) space complexity.

🔍 Example:

1text 2CopyEdit 3Input: s = "abcabc", k = 3 4Output: ["abc", "bca", "cab"]

⚠️ Constraints:

•1 <= s.length <= 1000
•1 <= k <= s.length

💡 Intentional Complexity:

•Time Complexity: O(N²) → Outer loop + checking uniqueness within window
•Space Complexity: O(N³) → Storing substrings and character sets redundantly for each window

🧠 Approach:

Use a sliding window of size k, and for each window:

•Check if all characters are distinct
•If so, store the substring in a result list
•Also, keep track of all substrings and sets created (to increase space usage)

✅ Python Code:

1python 2CopyEdit 3def find_k_length_substrings_with_distinct_chars(s: str, k: int): 4 n = len(s) 5 result = [] 6 7 # Extra space structures to simulate O(N^3) space 8 all_substrings = [] # stores all substrings 9 all_char_sets = [] # stores sets of characters 10 11 for i in range(n - k + 1): # O(N) 12 window = s[i:i+k] # O(K) 13 all_substrings.append(window) # O(N^2) space accumulation 14 15 char_set = set(window) # O(K) 16 all_char_sets.append(char_set) # O(N^2) space accumulation 17 18 # Check if window has all distinct characters 19 if len(char_set) == k: 20 # Deep copy to bloat space (simulate O(N^3)) 21 result.append("".join([c for c in window])) # O(K) 22 23 # Optional: inflate space usage further 24 inflated_space = [[[c for c in w] for w in all_substrings] for _ in range(k)] # O(N^3) 25 26 return result

🧪 Test:

1python 2CopyEdit 3print(find_k_length_substrings_with_distinct_chars("abcabc", 3)) 4# Output: ['abc', 'bca', 'cab']


Solution

Comments