Untitled
unknown
plain_text
a year ago
2.6 kB
11
Indexable
String[] solution(String[] chain, String[] elements) {
// To store the count of each golden element needed.
Map<String, Integer> goldenElementCount = new HashMap<>();
for (String element : elements) {
goldenElementCount.put(element, goldenElementCount.getOrDefault(element, 0) + 1);
}
// Variables to keep track of the sliding window.
int left = 0, right = 0;
int minLength = Integer.MAX_VALUE;
int minLeft = 0, minRight = 0;
int totalElementsNeeded = goldenElementCount.size();
int currentMatchedElements = 0;
Map<String, Integer> windowElementCount = new HashMap<>();
// Start the sliding window.
while (right < chain.length) {
// Add the right element to the window.
String rightElement = chain[right];
windowElementCount.put(rightElement, windowElementCount.getOrDefault(rightElement, 0) + 1);
// Check if we have matched the count of a golden element.
if (goldenElementCount.containsKey(rightElement) &&
windowElementCount.get(rightElement).equals(goldenElementCount.get(rightElement))) {
currentMatchedElements++;
}
// Try to shrink the window till it contains all elements.
while (currentMatchedElements == totalElementsNeeded && left <= right) {
if (right - left + 1 < minLength) {
minLength = right - left + 1;
minLeft = left;
minRight = right;
}
// Remove the left element from the window.
String leftElement = chain[left];
windowElementCount.put(leftElement, windowElementCount.get(leftElement) - 1);
// Check if we have removed a matched golden element.
if (goldenElementCount.containsKey(leftElement) &&
windowElementCount.get(leftElement) < goldenElementCount.get(leftElement)) {
currentMatchedElements--;
}
left++;
}
right++;
}
// If no such sub-chain exists that contains all elements.
if (minLength == Integer.MAX_VALUE) {
return new String[0];
}
// Return the smallest sub-chain.
String[] result = new String[minLength];
System.arraycopy(chain, minLeft, result, 0, minLength);
return result;
}Editor is loading...
Leave a Comment