Skip to content

Commit

Permalink
Merge branch 'main' into patch-3
Browse files Browse the repository at this point in the history
  • Loading branch information
shriyadindi authored Nov 6, 2024
2 parents e6df44a + 116b919 commit edbc6b8
Show file tree
Hide file tree
Showing 24 changed files with 1,469 additions and 198 deletions.
287 changes: 147 additions & 140 deletions README.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/DSA-Problem-Solution/Contains_duplicate.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ int main() {
```
## Approach and code explanation
**Using a Set for Uniqueness:**
- A set data structure inherently stores unique values. In C++, we use an unordered_set for this purpose, which allows us to:
- A set data structure inherently stores unique values. In C++, we used an unordered_set for this purpose, which allows us to:
Insert elements in O(1) average time.
Check if an element exists (lookup) in O(1) average time.
Expand Down
59 changes: 59 additions & 0 deletions docs/DSA-Problem-Solution/Convert Date to Binary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
---
id: date-to-binary-conversion
title: DSA Problem Solution
sidebar_label: DSA Problem Solution
sidebar-position: 1
description: The "Date to Binary Conversion" problem on LeetCode typically involves converting a given date into its binary representation.
tags: [DSA, leetcode, problem-solving]
---

# Leetcode: Problem-3280

## Description:

You are given a string ``date`` representing a Gregorian calendar date in the ``yyyy-mm-dd`` format.
``date`` can be written in its binary representation obtained by converting year, month, and day to their binary representations without any leading zeroes and writing them down in ``year-month-day`` format.
Return the binary representation of ``date``.

**Example 1:**
Input: date = "2080-02-29"
Output: "100000100000-10-11101"

**Explanation:**
100000100000, 10, and 11101 are the binary representations of 2080, 02, and 29 respectively.

**Example 2:**
Input: date = "1900-01-01"
Output: "11101101100-1-1"

**Explanation:**
11101101100, 1, and 1 are the binary representations of 1900, 1, and 1 respectively.

## Steps:
**1. Date Input:** Given a date in the format YYYY-MM-DD.

**2. Binary Conversion:**

• Convert the year (YYYY) to binary.
• Convert the month (MM) to binary.
• Convert the day (DD) to binary.

**3. Output:** Provide the combined binary representation.

# Solution in Java

```java
class Solution {
public String convertDateToBinary(String date) {
String[] parts = date.split("-");
int year = Integer.parseInt(parts[0]);
int month = Integer.parseInt(parts[1]);
int day = Integer.parseInt(parts[2]);

String yearBinary = Integer.toBinaryString(year);
String monthBinary = Integer.toBinaryString(month);
String dayBinary = Integer.toBinaryString(day);
return yearBinary + "-" + monthBinary + "-" + dayBinary;
}
}
```
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
Loading

0 comments on commit edbc6b8

Please sign in to comment.