Skip to content

Commit

Permalink
Merge pull request #1883 from T-Fathima/update
Browse files Browse the repository at this point in the history
Added java codes to Sliding window folder
  • Loading branch information
ajay-dhangar authored Nov 6, 2024
2 parents 72b6f32 + 8280048 commit 116b919
Show file tree
Hide file tree
Showing 6 changed files with 261 additions and 0 deletions.
38 changes: 38 additions & 0 deletions docs/Sliding-Window/character-replacement.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,41 @@ int main() {
return 0;
}
```
### Java Code Implementation:
```java
import java.util.HashMap;
public class CharacterReplacement {
public static int characterReplacement(String s, int k) {
HashMap<Character, Integer> count = new HashMap<>();
int left = 0, maxCount = 0, maxLength = 0;
for (int right = 0; right < s.length(); right++) {
char rightChar = s.charAt(right);
count.put(rightChar, count.getOrDefault(rightChar, 0) + 1);
maxCount = Math.max(maxCount, count.get(rightChar));
while (right - left + 1 - maxCount > k) {
char leftChar = s.charAt(left);
count.put(leftChar, count.get(leftChar) - 1);
left++;
}
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
public static void main(String[] args) {
String s = "AABABBA";
int k = 1;
int result = characterReplacement(s, k);
System.out.println("The length of the longest substring is: " + result);
}
}
```
39 changes: 39 additions & 0 deletions docs/Sliding-Window/introduction-to-sliding-window.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,45 @@ result = max_sum_subarray(arr, k)
print(f"Maximum sum of subarray of size {k}: {result}")
```

### Java Code Implementation

```java
public class MaxSumSubarray {

public static int maxSumSubarray(int[] arr, int k) {
int n = arr.length;
if (n < k) {
System.out.println("Invalid input, array size is smaller than k.");
return -1;
}

int maxSum = -1; // Set max sum
int currentSum = 0;

// Compute the sum of the first window
for (int i = 0; i < k; i++) {
currentSum += arr[i];
}
maxSum = currentSum;

// Slide the window across the array
for (int i = k; i < n; i++) {
currentSum += arr[i] - arr[i - k]; // Slide the window
maxSum = Math.max(maxSum, currentSum); // Update max sum
}

return maxSum;
}

public static void main(String[] args) {
int[] arr = {2, 1, 5, 1, 3, 2};
int k = 3;
int result = maxSumSubarray(arr, k);
System.out.println("Maximum sum of subarray of size " + k + ": " + result);
}
}
```

### Explanation:
The first `for` loop calculates the sum of the first subarray (window) of size `k`.
The second `for` loop slides the window one element at a time, adjusting the sum by adding the new element and removing the element that is no longer in the window.
Expand Down
45 changes: 45 additions & 0 deletions docs/Sliding-Window/longest-repeating-character-replacement.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,51 @@ int main() {
return 0;
}
```
### Java Code Implementation:
```java
import java.util.*;
public class CharacterReplacement {
public static int characterReplacement(String s, int k) {
int maxLen = 0; // Tracks the length of the longest valid substring
int maxFreq = 0; // Tracks the frequency of the most common character in the window
int[] charCount = new int[26]; // Frequency count for each character
int left = 0; // Left pointer for the sliding window
for (int right = 0; right < s.length(); ++right) {
// Update the frequency of the current character
charCount[s.charAt(right) - 'A']++;
maxFreq = Math.max(maxFreq, charCount[s.charAt(right) - 'A']); // Update maxFreq
// Check if the current window is valid
int windowSize = right - left + 1;
if (windowSize - maxFreq > k) {
// If the window is not valid, shrink the window from the left
charCount[s.charAt(left) - 'A']--;
left++;
}
// Update the maximum valid window size
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
public static void main(String[] args) {
String s = "AABABBA";
int k = 1;
int result = characterReplacement(s, k);
System.out.println("The length of the longest repeating character substring is: " + result);
}
}
```

## Explanation:
Sliding Window:
We maintain a sliding window using two pointers, left and right, to explore the string and check valid substrings. As we move the right pointer, we add the new character to our frequency count and adjust the window size to find the longest valid substring.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,52 @@ print(f"Longest substring with {k} distinct characters: {longest_substring_k_dis
```


### Java Code Implementation:
```java
import java.util.HashMap;

public class LongestSubstringKDistinct {

public static int longestSubstringKDistinct(String s, int k) {
if (s == null || k == 0) {
return 0;
}

HashMap<Character, Integer> charFreq = new HashMap<>();
int maxLength = 0;
int left = 0;

for (int right = 0; right < s.length(); right++) {
char rightChar = s.charAt(right);
charFreq.put(rightChar, charFreq.getOrDefault(rightChar, 0) + 1);

// Shrink the window if we have more than 'k' distinct characters
while (charFreq.size() > k) {
char leftChar = s.charAt(left);
charFreq.put(leftChar, charFreq.get(leftChar) - 1);

if (charFreq.get(leftChar) == 0) {
charFreq.remove(leftChar); // Remove from map if frequency becomes 0
}
left++; // Move the left pointer
}

// Update the maximum length of the valid window
maxLength = Math.max(maxLength, right - left + 1);
}

return maxLength;
}

public static void main(String[] args) {
String s = "araaci";
int k = 2;
System.out.println("Longest substring with " + k + " distinct characters: " + longestSubstringKDistinct(s, k));
}
}
```


## Explanation:
We use a sliding window that moves over the string by adjusting the right pointer to include more characters.
The charFreq map keeps track of the frequency of characters in the window.
Expand Down
38 changes: 38 additions & 0 deletions docs/Sliding-Window/maximum-sum-subarray-size-K.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,44 @@ arr = [2, 1, 5, 1, 3, 2]
k = 3
result = max_sum_subarray(arr, k)
print(f"Maximum sum of subarray of size {k}: {result}")
```

### Java Code Implementation:
```java
public class MaxSumSubarray {

public static int maxSumSubarray(int[] arr, int k) {
int n = arr.length;
if (n < k) {
System.out.println("Invalid input, array size is smaller than k.");
return -1;
}

int maxSum = Integer.MIN_VALUE;
int currentSum = 0;

// Compute the sum of the first window
for (int i = 0; i < k; i++) {
currentSum += arr[i];
}
maxSum = currentSum;

// Slide the window across the array
for (int i = k; i < n; i++) {
currentSum += arr[i] - arr[i - k]; // Slide the window
maxSum = Math.max(maxSum, currentSum); // Update max sum
}

return maxSum;
}

public static void main(String[] args) {
int[] arr = {2, 1, 5, 1, 3, 2};
int k = 3;
int result = maxSumSubarray(arr, k);
System.out.println("Maximum sum of subarray of size " + k + ": " + result);
}
}
```

## Explanation:
Expand Down
55 changes: 55 additions & 0 deletions docs/Sliding-Window/minimize-maximum-of-two-arrays.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,61 @@ result = minimize_max_of_two_arrays(A, B)
print(f"The minimum maximum value is: {result}")
```

### Java Code Implementation:

```java
import java.util.Arrays;

public class MinimizeMaxOfTwoArrays {

// Helper function to check if x can be the minimum maximum
private static boolean canMinimize(int x, int[] A, int[] B) {
int idxA = bisectRight(A, x);
int idxB = bisectRight(B, x);
return idxA > 0 && idxB > 0; // There exists elements <= x in both arrays
}

// Custom binary search helper to find the first element greater than x
private static int bisectRight(int[] array, int x) {
int low = 0, high = array.length;
while (low < high) {
int mid = low + (high - low) / 2;
if (array[mid] <= x) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}

public static int minimizeMaxOfTwoArrays(int[] A, int[] B) {
int low = Math.min(A[0], B[0]); // Lower bound of the search space
int high = Math.max(A[A.length - 1], B[B.length - 1]); // Upper bound of the search space
int result = high;

while (low <= high) {
int mid = low + (high - low) / 2;
if (canMinimize(mid, A, B)) {
result = mid; // mid can be a candidate for the minimum maximum
high = mid - 1; // Try to minimize further
} else {
low = mid + 1; // Increase the lower bound
}
}

return result;
}

public static void main(String[] args) {
int[] A = {1, 4, 6};
int[] B = {2, 5, 8};
int result = minimizeMaxOfTwoArrays(A, B);
System.out.println("The minimum maximum value is: " + result);
}
}
```


## Explanation:
Binary Search on Maximum Value:
Expand Down

0 comments on commit 116b919

Please sign in to comment.