Amazon Online Assessment (OA) 2021 - Substrings of Size K with Distinct Characters | HackerRank SHL
Solution
1defsubstrings(s: str, k: int) -> list[str]:2 found = set()
3 res = []
45# char -> index of (only) occurence in substring6 occur = {}
7# start index of substring8 start = 09# end index of substring10 end = 011while end < len(s):
12 ch = s[end]
13# ensure s[start:end] has length <= k and distinct chars14 new_start = occur.get(ch, end - k)
15while start <= new_start:
16 occur.pop(s[start])
17 start += 11819 occur[ch] = end
20 end += 121if end - start < k:
22continue23 sub = s[start:end]
24if sub notin found:
25 found.add(sub)
26 res.append(sub)
2728return res
2930if __name__ == "__main__":
31 s = input()
32 k = int(input())
33 res = substrings(s, k)
34print(" ".join(res))
35
1import java.util.ArrayList;
2import java.util.HashMap;
3import java.util.HashSet;
4import java.util.List;
5import java.util.Scanner;
67classSolution{
8publicstatic List<String> substrings(String s, int k){
9 HashSet<String> found = new HashSet<>();
10 ArrayList<String> res = new ArrayList<>();
1112// char -> index of (only) occurence in substring13 HashMap<Character, Integer> occur = new HashMap<>();
14// start index of substring15int start = 0;
16// end index of substring17int end = 0;
18while (end < s.length()) {
19char ch = s.charAt(end);
20// ensure s[start:end] has length <= k and distinct chars21int newStart = occur.getOrDefault(ch, end - k);
22while (start <= newStart) {
23 occur.remove(s.charAt(start));
24 start++;
25 }
2627 occur.put(ch, end);
28 end++;
29if (end - start < k)
30continue;
31 String sub = s.substring(start, end);
32if (!found.contains(sub)) {
33 found.add(sub);
34 res.add(sub);
35 }
36 }
3738return res;
39 }
4041publicstaticvoidmain(String[] args){
42 java.util.Scanner scanner = new java.util.Scanner(System.in);
43 String s = scanner.nextLine();
44int k = Integer.parseInt(scanner.nextLine());
45 scanner.close();
46 List<String> res = substrings(s, k);
47 System.out.println(String.join(" ", res));
48 }
49}
50