|
| 1 | +package com.thealgorithms.slidingwindow; |
| 2 | + |
| 3 | +/** |
| 4 | + * The Longest Subarray with Sum Less Than or Equal to k algorithm finds the length |
| 5 | + * of the longest subarray whose sum is less than or equal to a given value k. |
| 6 | + * |
| 7 | + * <p> |
| 8 | + * Worst-case performance O(n) |
| 9 | + * Best-case performance O(n) |
| 10 | + * Average performance O(n) |
| 11 | + * Worst-case space complexity O(1) |
| 12 | + * |
| 13 | + * @author https://github.com/Chiefpatwal |
| 14 | + */ |
| 15 | +class Solution { |
| 16 | + public static String minWindow(String s, String t) { |
| 17 | + if (s.length() < t.length()) return ""; |
| 18 | + |
| 19 | + HashMap<Character, Integer> tFreq = new HashMap<>(); |
| 20 | + for (char c : t.toCharArray()) { |
| 21 | + tFreq.put(c, tFreq.getOrDefault(c, 0) + 1); |
| 22 | + } |
| 23 | + |
| 24 | + HashMap<Character, Integer> windowFreq = new HashMap<>(); |
| 25 | + int left = 0, right = 0, minLen = Integer.MAX_VALUE, count = 0; |
| 26 | + String result = ""; |
| 27 | + |
| 28 | + while (right < s.length()) { |
| 29 | + char c = s.charAt(right); |
| 30 | + windowFreq.put(c, windowFreq.getOrDefault(c, 0) + 1); |
| 31 | + |
| 32 | + if (tFreq.containsKey(c) && windowFreq.get(c).intValue() <= tFreq.get(c).intValue()) { |
| 33 | + count++; |
| 34 | + } |
| 35 | + |
| 36 | + while (count == t.length()) { |
| 37 | + if (right - left + 1 < minLen) { |
| 38 | + minLen = right - left + 1; |
| 39 | + result = s.substring(left, right + 1); |
| 40 | + } |
| 41 | + |
| 42 | + char leftChar = s.charAt(left); |
| 43 | + windowFreq.put(leftChar, windowFreq.get(leftChar) - 1); |
| 44 | + |
| 45 | + if (tFreq.containsKey(leftChar) && windowFreq.get(leftChar) < tFreq.get(leftChar)) { |
| 46 | + count--; |
| 47 | + } |
| 48 | + |
| 49 | + left++; |
| 50 | + } |
| 51 | + right++; |
| 52 | + } |
| 53 | + return result; |
| 54 | + } |
| 55 | +} |
0 commit comments