Skip to content

Commit

Permalink
Merge pull request #1168 from mah-shamim/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
mah-shamim authored Jan 17, 2025
2 parents c84875b + 3e80048 commit 6ab64fb
Show file tree
Hide file tree
Showing 415 changed files with 35,263 additions and 649 deletions.
10 changes: 10 additions & 0 deletions .github/ISSUE_TEMPLATE/custom.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
name: Custom issue template
about: Describe this issue template's purpose here.
title: ''
labels: ''
assignees: ''

---


2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/feature_request.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
labels: question
assignees: ''

---
Expand Down
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
.idea/
.vscode/

automate_git.bat
auto_commit.sh
auto_commit.bat
*.iml
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@
Php-based LeetCode algorithm problem solutions, regularly updated.


![Alt](https://repobeats.axiom.co/api/embed/9f698d3cdb218feb946714e458ac140a276b39a5.svg "Repobeats analytics image")
![Repobeats analytics image](https://repobeats.axiom.co/api/embed/9f698d3cdb218feb946714e458ac140a276b39a5.svg "Repobeats analytics image")



56 changes: 56 additions & 0 deletions algorithms/000040-combination-sum-ii/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
40\. Combination Sum II

**Difficulty:** Medium

**Topics:** `Array`, `Backtracking`

Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`.

Each number in `candidates` may only be used **once** in the combination.

**Note:** The solution set must not contain duplicate combinations.

**Example 1:**

- **Input:** candidates = [10,1,2,7,6,1,5], target = 8
- **Output:** [[1,1,6], [1,2,5], [1,7], [2,6]]

**Example 2:**

- **Input:** candidates = [2,5,2,1,2], target = 5
- **Output:** [[1,2,2], [5]]

**Constraints:**

- <code>1 <= candidates.length <= 100</code>
- <code>1 <= candidates[i] <= 50</code>
- <code>1 <= target <= 30</code>


**Solution:**


We can use a backtracking approach. The key idea is to sort the array first to handle duplicates easily and then explore all possible combinations using backtracking.

Let's implement this solution in PHP: **[40. Combination Sum II](https://github.com/mah-shamim/leet-code-in-php/tree/main/algorithms/000040-combination-sum-ii/solution.php)**

### Explanation:

1. **Sorting**: The candidates array is sorted to handle duplicates easily and to ensure combinations are formed in a sorted order.
2. **Backtracking**: The `backtrack` function is used to explore all possible combinations.
- If the `target` becomes zero, we add the current combination to the result.
- We iterate over the candidates starting from the current index. If a candidate is the same as the previous one, we skip it to avoid duplicate combinations.
- We subtract the current candidate from the target and recursively call the `backtrack` function with the new target and the next index.
- The recursive call continues until we either find a valid combination or exhaust all possibilities.
3. **Pruning**: If the candidate exceeds the target, we break out of the loop early since further candidates will also exceed the target.

This code will output all unique combinations that sum up to the target while ensuring that each candidate is used only once in each combination.

**Contact Links**

If you found this series helpful, please consider giving the **[repository](https://github.com/mah-shamim/leet-code-in-php)** a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

- **[LinkedIn](https://www.linkedin.com/in/arifulhaque/)**
- **[GitHub](https://github.com/mah-shamim)**
44 changes: 44 additions & 0 deletions algorithms/000040-combination-sum-ii/solution.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

class Solution {

/**
* @param Integer[] $candidates
* @param Integer $target
* @return Integer[][]
*/
function combinationSum2($candidates, $target) {
sort($candidates);
$result = [];
$this->backtrack($candidates, $target, 0, [], $result);
return $result;
}

/**
* @param $candidates
* @param $target
* @param $start
* @param $currentCombination
* @param $result
* @return void
*/
function backtrack($candidates, $target, $start, $currentCombination, &$result) {
if ($target == 0) {
$result[] = $currentCombination;
return;
}

for ($i = $start; $i < count($candidates); $i++) {
if ($i > $start && $candidates[$i] == $candidates[$i - 1]) {
continue; // Skip duplicates
}

if ($candidates[$i] > $target) {
break; // No need to continue if the candidate exceeds the target
}

self::backtrack($candidates, $target - $candidates[$i], $i + 1, array_merge($currentCombination, [$candidates[$i]]), $result);
}
}

}
81 changes: 80 additions & 1 deletion algorithms/000075-sort-colors/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

Medium

**Topics:** `Array`, `Two Pointers`, `Sorting`

Given an array `nums` with `n` objects colored red, white, or blue, sort them [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers `0`, `1`, and `2` to represent the color red, white, and blue, respectively.
Expand All @@ -24,4 +26,81 @@ You must solve this problem without using the library's sort function.
- <code>1 <= n <= 300</code>
- `nums[i]` is either `0`, `1`, or `2`.

**Follow-up:** Could you come up with a one-pass algorithm using only constant extra space?
**Follow-up:** Could you come up with a one-pass algorithm using only constant extra space?

**Hint:**
1. A rather straight forward solution is a two-pass algorithm using counting sort.
2. Iterate the array counting number of 0's, 1's, and 2's.
3. Overwrite array with the total number of 0's, then 1's and followed by 2's.


**Solution:**


To solve this problem, we can follow these steps:

The goal is to sort the array `nums` with elements representing the colors red (0), white (1), and blue (2) in one pass, using constant extra space.

### Approach:

The most efficient way to solve this problem is by using the Dutch National Flag algorithm, which is a one-pass algorithm with constant extra space. The idea is to use three pointers:
- `low` to track the position for the next 0 (red),
- `mid` to traverse the array,
- `high` to track the position for the next 2 (blue).

### Algorithm:
1. Initialize three pointers:
- `low` at the start (0),
- `mid` at the start (0),
- `high` at the end (n-1) of the array.

2. Traverse the array with `mid`:
- If `nums[mid]` is `0` (red), swap `nums[mid]` with `nums[low]`, then increment both `low` and `mid`.
- If `nums[mid]` is `1` (white), move `mid` to the next element.
- If `nums[mid]` is `2` (blue), swap `nums[mid]` with `nums[high]` and decrement `high`.

3. Continue until `mid` exceeds `high`.

This algorithm sorts the array in-place with a single pass.

Let's implement this solution in PHP: **[75. Sort Colors](https://github.com/mah-shamim/leet-code-in-php/tree/main/algorithms/000075-sort-colors/solution.php)**

```php
<?php
// Example usage:
$nums1 = [2, 0, 2, 1, 1, 0];
sortColors($nums1);
print_r($nums1); // Output: [0, 0, 1, 1, 2, 2]

$nums2 = [2,0,1];
sortColors($nums2);
print_r($nums2); // Output: [0,1,2]

?>
```

### Explanation:

1. **Initialization:**
- `low` starts at the beginning (`0`).
- `mid` starts at the beginning (`0`).
- `high` starts at the end (`n-1`).

2. **Loop Through Array:**
- If `nums[mid]` is `0`, it swaps with `nums[low]` because `0` should be at the front. Both pointers `low` and `mid` are then incremented.
- If `nums[mid]` is `1`, it is already in the correct position, so only `mid` is incremented.
- If `nums[mid]` is `2`, it swaps with `nums[high]` because `2` should be at the end. Only `high` is decremented, while `mid` stays the same to check the swapped element.

3. **Completion:**
- The loop continues until `mid` passes `high`, ensuring that the array is sorted in the order of `0`, `1`, and `2`.

This approach is optimal with O(n) time complexity and O(1) space complexity.

**Contact Links**

If you found this series helpful, please consider giving the **[repository](https://github.com/mah-shamim/leet-code-in-php)** a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

- **[LinkedIn](https://www.linkedin.com/in/arifulhaque/)**
- **[GitHub](https://github.com/mah-shamim)**
37 changes: 22 additions & 15 deletions algorithms/000075-sort-colors/solution.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,29 @@ class Solution {
* @param Integer[] $nums
* @return NULL
*/
function sortColors(array &$nums) {
$l = 0; // The next 0 should be placed in l.
$r = count($nums) - 1; // The next 2 should be placed in r.
function sortColors(&$nums) {
$low = 0;
$mid = 0;
$high = count($nums) - 1;

for ($i = 0; $i <= $r;) {
if ($nums[$i] == 0) {
list($nums[$i], $nums[$l]) = array($nums[$l], $nums[$i]);
$i++;
$l++;
} elseif ($nums[$i] == 1) {
$i++;
} else {
// We may swap a 0 to index i, but we're still not sure whether this 0
// is placed in the correct index, so we can't move pointer i.
list($nums[$i], $nums[$r]) = array($nums[$r], $nums[$i]);
$r--;
while ($mid <= $high) {
if ($nums[$mid] == 0) {
// Swap nums[low] and nums[mid]
$temp = $nums[$low];
$nums[$low] = $nums[$mid];
$nums[$mid] = $temp;

$low++;
$mid++;
} elseif ($nums[$mid] == 1) {
$mid++;
} else { // nums[$mid] == 2
// Swap nums[mid] and nums[high]
$temp = $nums[$high];
$nums[$high] = $nums[$mid];
$nums[$mid] = $temp;

$high--;
}
}
}
Expand Down
84 changes: 82 additions & 2 deletions algorithms/000078-subsets/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
78\. Subsets

Medium
**Difficulty:** Medium

**Topics:** `Array`, `Backtracking`, `Bit Manipulation`

Given an integer array `nums` of **unique** elements, return _all possible subsets[^1] (the power set)._

Expand All @@ -23,4 +25,82 @@ The solution set **must not** contain duplicate subsets. Return the solution in
- <code>-10 <= nums[i] <= 10</code>
- All the numbers of `nums` are **unique**.

[^1]: **Subset** <code>A **subset** of an array is a selection of elements (possibly none) of the array.</code>
[^1]: **Subset** <code>A **subset** of an array is a selection of elements (possibly none) of the array.</code>

**Solution:**


To solve this problem, we can follow these steps:

Let's implement this solution in PHP: **[78. Subsets](https://github.com/mah-shamim/leet-code-in-php/tree/main/algorithms/000078-subsets/solution.php)**

```php
<?php
// Test the function with example inputs
print_r(subsets([1,2,3])); // Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
print_r(subsets([0])); // Output: [[],[0]]
?>
```

### Explanation:

1. **Function Signature and Input**:
- The function `subsets()` takes an array of integers `nums` as input and returns an array of arrays, where each inner array represents a subset of `nums`.
- The return type is `Integer[][]`, meaning an array of arrays of integers.

2. **Initialization**:
- `$ans = [[]];`: Initialize the result array `$ans` with an empty subset (`[]`). This is the base case where the subset is empty.

3. **Iterating Over Each Number**:
- `foreach($nums as $num)`: Loop through each number in the input array `nums`. For each number `num`, you'll generate new subsets by adding `num` to each of the existing subsets.

4. **Generating New Subsets**:
- `$ans_size = count($ans);`: Before modifying the `$ans` array, store its current size in `$ans_size`. This is necessary to prevent an infinite loop as new subsets are added.
- `for($i = 0; $i < $ans_size; $i++)`: Iterate over the current subsets stored in `$ans` up to `$ans_size`.
- `$cur = $ans[$i];`: Take the current subset.
- `$cur[] = $num;`: Append the current number `num` to this subset.
- `$ans[] = $cur;`: Add this new subset back into `$ans`.

5. **Return the Result**:
- `return $ans;`: After processing all numbers in `nums`, return the final array of all possible subsets.

### Example Execution:

Let's go through an example to see how it works.

- **Input**: `$nums = [1, 2]`
- **Initial State**: `$ans = [[]]`

**Iteration 1 (`num = 1`)**:
- `$ans_size = 1`: (Because there's only one subset, `[]`)
- For `i = 0`:
- `$cur = []`: Take the empty subset.
- `$cur[] = 1`: Append `1` to it, resulting in `[1]`.
- `$ans = [[], [1]]`: Add `[1]` to `$ans`.

**Iteration 2 (`num = 2`)**:
- `$ans_size = 2`: (Now there are two subsets: `[]` and `[1]`)
- For `i = 0`:
- `$cur = []`: Take the empty subset.
- `$cur[] = 2`: Append `2` to it, resulting in `[2]`.
- `$ans = [[], [1], [2]]`: Add `[2]` to `$ans`.
- For `i = 1`:
- `$cur = [1]`: Take the subset `[1]`.
- `$cur[] = 2`: Append `2` to it, resulting in `[1, 2]`.
- `$ans = [[], [1], [2], [1, 2]]`: Add `[1, 2]` to `$ans`.

**Final Result**:
- The function returns `[[], [1], [2], [1, 2]]`, which are all possible subsets of `[1, 2]`.

### Summary:

This function uses a dynamic approach to generate all subsets of an array by iteratively adding each element of the array to existing subsets. The time complexity is \(O(2^n)\), where \(n\) is the number of elements in the input array, because each element can either be included or excluded from each subset, resulting in \(2^n\) possible subsets.

**Contact Links**

If you found this series helpful, please consider giving the **[repository](https://github.com/mah-shamim/leet-code-in-php)** a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

- **[LinkedIn](https://www.linkedin.com/in/arifulhaque/)**
- **[GitHub](https://github.com/mah-shamim)**
Loading

0 comments on commit 6ab64fb

Please sign in to comment.