-
-
Notifications
You must be signed in to change notification settings - Fork 46.8k
Group anagram #10958
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Group anagram #10958
Changes from all commits
Commits
Show all changes
70 commits
Select commit
Hold shift + click to select a range
35c6c7e
Add: Matrix Prefix Sum
aayushsoni4 a8603ea
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] b21b10d
Changes made in Matrix Prefix Sum
aayushsoni4 322e45a
Merge branch 'master' of https://github.com/aayushsoni4/Python
aayushsoni4 89d32bd
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 2cee13c
Changes made in Matrix Prefix Sum
aayushsoni4 4e2e56e
Changes made in Matrix Prefix Sum
aayushsoni4 de886cf
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 336adf2
Changes made in Matrix Prefix Sum
aayushsoni4 28d9cfd
Changes made in Matrix Prefix Sum
aayushsoni4 b43f475
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 37718c7
Changes made in Matrix Prefix Sum
aayushsoni4 e5ee235
Merge branch 'master' of https://github.com/aayushsoni4/Python
aayushsoni4 e9403b2
Changes made in Matrix Prefix Sum
aayushsoni4 7d7e2e7
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] f987823
Changes made in Matrix Prefix Sum
aayushsoni4 c0e18be
Changes made in Matrix Prefix Sum
aayushsoni4 4ed2d72
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 157c744
Changes made in Matrix Prefix Sum
aayushsoni4 6e5c84c
Changes made in Matrix Prefix Sum
aayushsoni4 5c3a01f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 6b718c5
Changes made in Matrix Prefix Sum
aayushsoni4 2c78030
Merge branch 'master' of https://github.com/aayushsoni4/Python
aayushsoni4 11aa213
Changes made in Matrix Prefix Sum
aayushsoni4 3ab1ea6
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 97d1414
Changes made in Matrix Prefix Sum
aayushsoni4 14000b3
Changes made in Matrix Prefix Sum
aayushsoni4 0853c35
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] b01f637
Changes made in Matrix Prefix Sum
aayushsoni4 13d806e
Merge branch 'master' of https://github.com/aayushsoni4/Python
aayushsoni4 778df87
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] b568f9d
Changes made in Matrix Prefix Sum
aayushsoni4 b03426e
Merge branch 'master' of https://github.com/aayushsoni4/Python
aayushsoni4 aba2ef2
Changes made in Matrix Prefix Sum
aayushsoni4 6280be4
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 896f3a9
Changes made in Matrix Prefix Sum
aayushsoni4 abe5fb0
Merge branch 'master' of https://github.com/aayushsoni4/Python
aayushsoni4 01e6e1c
Changes made in Matrix Prefix Sum
aayushsoni4 27022eb
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 0d8007d
Changes made in Matrix Prefix Sum
aayushsoni4 bc5276d
Merge branch 'master' of https://github.com/aayushsoni4/Python
aayushsoni4 fbc4fa7
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] b9311e9
Changes made in Matrix Prefix Sum
aayushsoni4 14e51db
Merge branch 'master' of https://github.com/aayushsoni4/Python
aayushsoni4 9da4957
Add: Distinct Subsequences
aayushsoni4 b2f0756
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 61a2824
Changes made in Distinct Subsequences
aayushsoni4 ff23cb8
Changes made in Distinct Subsequences
aayushsoni4 3329261
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] fb935b2
Changes made in Distinct Subsequences
aayushsoni4 b7e51c9
Merge branch 'master' of https://github.com/aayushsoni4/Python
aayushsoni4 aaf1c3b
Changes made in Distinct Subsequences
aayushsoni4 e268227
Changes made in Distinct Subsequences
aayushsoni4 6ce845a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 7cb9ca2
Removed Distinct Subsequences
aayushsoni4 2eda0a9
Removed Distinct Subsequences
aayushsoni4 e01c863
Add: Generate Parentheses
aayushsoni4 c9d1d70
Add: Generate Parentheses
aayushsoni4 f037e2e
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] e9ac8f6
Add: Generate Parentheses
aayushsoni4 0d227a3
Merge branch 'Generate_Parentheses' of https://github.com/aayushsoni4…
aayushsoni4 26643c1
Add: Generate Parentheses
aayushsoni4 c93ee0c
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] a1c3658
Add: Generate Parentheses
aayushsoni4 09aa37f
Merge branch 'Generate_Parentheses' of https://github.com/aayushsoni4…
aayushsoni4 4042202
Add: Generate Parentheses
aayushsoni4 444dea5
Add: Group Anagram
aayushsoni4 c7ff6f5
Add: Group Anagram
aayushsoni4 2499747
Add: Group Anagram
aayushsoni4 df404fd
Add: Group Anagram
aayushsoni4 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
""" | ||
author: Aayush Soni | ||
Given n pairs of parentheses, write a function to generate all | ||
combinations of well-formed parentheses. | ||
Input: n = 2 | ||
Output: ["(())","()()"] | ||
Leetcode link: https://leetcode.com/problems/generate-parentheses/description/ | ||
""" | ||
|
||
|
||
def backtrack( | ||
partial: str, open_count: int, close_count: int, n: int, result: list[str] | ||
aayushsoni4 marked this conversation as resolved.
Show resolved
Hide resolved
aayushsoni4 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) -> None: | ||
""" | ||
Generate valid combinations of balanced parentheses using recursion. | ||
|
||
:param partial: A string representing the current combination. | ||
:param open_count: An integer representing the count of open parentheses. | ||
:param close_count: An integer representing the count of close parentheses. | ||
:param n: An integer representing the total number of pairs. | ||
:param result: A list to store valid combinations. | ||
:return: None | ||
|
||
This function uses recursion to explore all possible combinations, | ||
ensuring that at each step, the parentheses remain balanced. | ||
|
||
Example: | ||
>>> result = [] | ||
>>> backtrack("", 0, 0, 2, result) | ||
>>> result | ||
['(())', '()()'] | ||
""" | ||
if len(partial) == 2 * n: | ||
# When the combination is complete, add it to the result. | ||
result.append(partial) | ||
return | ||
|
||
if open_count < n: | ||
# If we can add an open parenthesis, do so, and recurse. | ||
backtrack(partial + "(", open_count + 1, close_count, n, result) | ||
|
||
if close_count < open_count: | ||
# If we can add a close parenthesis (it won't make the combination invalid), | ||
# do so, and recurse. | ||
backtrack(partial + ")", open_count, close_count + 1, n, result) | ||
|
||
|
||
def generate_parenthesis(n: int) -> list[str]: | ||
aayushsoni4 marked this conversation as resolved.
Show resolved
Hide resolved
aayushsoni4 marked this conversation as resolved.
Show resolved
Hide resolved
aayushsoni4 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Generate valid combinations of balanced parentheses for a given n. | ||
|
||
:param n: An integer representing the number of pairs of parentheses. | ||
:return: A list of strings with valid combinations. | ||
|
||
This function uses a recursive approach to generate the combinations. | ||
|
||
Time Complexity: O(2^(2n)) - In the worst case, we have 2^(2n) combinations. | ||
Space Complexity: O(n) - where 'n' is the number of pairs. | ||
|
||
Example 1: | ||
>>> generate_parenthesis(3) | ||
['((()))', '(()())', '(())()', '()(())', '()()()'] | ||
|
||
Example 2: | ||
>>> generate_parenthesis(1) | ||
['()'] | ||
""" | ||
|
||
result = [] | ||
backtrack("", 0, 0, n, result) | ||
return result | ||
|
||
|
||
if __name__ == "__main__": | ||
import doctest | ||
|
||
doctest.testmod() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
""" | ||
Python Program to find prefix sum of a 2D array | ||
""" | ||
|
||
|
||
def calculate_prefix_sum(matrix: list[list[int]]) -> list[list[int]]: | ||
""" | ||
Calculate the prefix sum of a 2D matrix. | ||
Prefix Sum Formula: | ||
prefix_sum[i][j] = prefix_sum[i - 1][j] + prefix_sum[i][j - 1] | ||
- prefix_sum[i - 1][j - 1] + matrix[i][j] | ||
|
||
:param matrix: A 2D matrix. | ||
:return: A matrix containing the prefix sums. | ||
|
||
>>> calculate_prefix_sum([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) | ||
[[1, 2, 3], [2, 4, 6], [3, 6, 9]] | ||
|
||
>>> calculate_prefix_sum([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) | ||
[[1, 3, 6], [5, 12, 21], [12, 27, 45]] | ||
""" | ||
rows = len(matrix) | ||
cols = len(matrix[0]) | ||
|
||
# Initialize the prefix sum matrix with zeros, with the | ||
# same dimensions as the original matrix. | ||
prefix_sum = [[0 for _ in range(cols)] for _ in range(rows)] | ||
|
||
# Calculate the prefix sum for the top-left cell. | ||
prefix_sum[0][0] = matrix[0][0] | ||
|
||
# Calculate cumulative sums for the first row. | ||
for i in range(1, cols): | ||
prefix_sum[0][i] = prefix_sum[0][i - 1] + matrix[0][i] | ||
|
||
# Calculate cumulative sums for the first column. | ||
for i in range(1, rows): | ||
prefix_sum[i][0] = prefix_sum[i - 1][0] + matrix[i][0] | ||
|
||
# Update the values in the cells using the general formula. | ||
for i in range(1, rows): | ||
for j in range(1, cols): | ||
# The value in each cell is the sum of: | ||
# - The cell above it | ||
# - The cell to the left of it | ||
# - Subtracting the overlapping cell | ||
# - Adding the value from the original matrix | ||
prefix_sum[i][j] = ( | ||
prefix_sum[i - 1][j] | ||
+ prefix_sum[i][j - 1] | ||
- prefix_sum[i - 1][j - 1] | ||
+ matrix[i][j] | ||
) | ||
|
||
return prefix_sum | ||
|
||
|
||
def display_matrix(matrix: list[list[int]]) -> None: | ||
""" | ||
Display a 2D matrix. | ||
|
||
:param matrix: A 2D matrix. | ||
|
||
Display a 2D matrix by printing each row's elements separated by spaces. | ||
|
||
>>> display_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) | ||
1 2 3 | ||
4 5 6 | ||
7 8 9 | ||
|
||
>>> display_matrix([[10, 20, 30], [40, 50, 60]]) | ||
10 20 30 | ||
40 50 60 | ||
""" | ||
for row in matrix: | ||
# Join the elements of each row with spaces and print the result. | ||
print(" ".join(map(str, row))) | ||
|
||
|
||
if __name__ == "__main__": | ||
matrix = [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] | ||
# Calculate the prefix sum of the 2D matrix | ||
prefix_sum_matrix = calculate_prefix_sum(matrix) | ||
|
||
# Display the prefix sum matrix | ||
display_matrix(prefix_sum_matrix) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
""" | ||
author: Aayush Soni | ||
Given an array of strings strs, group the anagrams together. | ||
You can return the answer in any order. | ||
|
||
An Anagram is a word or phrase formed by rearranging the letters of | ||
a different word or phrase, typically using all the original letters exactly once. | ||
|
||
Leetcode link: https://leetcode.com/problems/group-anagrams/description/ | ||
""" | ||
|
||
|
||
def group_anagrams(words: list[str]) -> dict[str, list[str]]: | ||
""" | ||
Group anagrams in a list of words. | ||
|
||
This function takes a list of words and groups them | ||
based on whether they are anagrams of each other. | ||
|
||
Examples: | ||
>>> group_anagrams(["cat", "dog", "tac", "god", "act"]) | ||
{'act': ['cat', 'tac', 'act'], 'dgo': ['dog', 'god']} | ||
|
||
>>> group_anagrams(["listen", "silent", "hello", "world"]) | ||
{'eilnst': ['listen', 'silent'], 'ehllo': ['hello'], 'dlorw': ['world']} | ||
""" | ||
|
||
grouped_words: dict[str, list[str]] = {} | ||
|
||
# Put all anagram words together in a dictionary | ||
# where the key is the sorted word | ||
for word in words: | ||
sorted_word = "".join(sorted(word)) | ||
if sorted_word not in grouped_words: | ||
grouped_words[sorted_word] = [word] | ||
else: | ||
grouped_words[sorted_word].append(word) | ||
|
||
return grouped_words | ||
|
||
|
||
if __name__ == "__main__": | ||
words = ["cat", "dog", "tac", "god", "act"] | ||
groups = group_anagrams(words) | ||
|
||
# Sort the groups for consistent output | ||
sorted_groups = sorted(groups) | ||
|
||
for key in sorted_groups: | ||
group = groups[key] | ||
print(" ".join(group)) | ||
|
||
import doctest | ||
|
||
doctest.testmod() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.