Skip to content

[pull] master from TheAlgorithms:master #51

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

Merged
merged 4 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions backtracking/word_break.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""
Word Break Problem is a well-known problem in computer science.
Given a string and a dictionary of words, the task is to determine if
the string can be segmented into a sequence of one or more dictionary words.

Wikipedia: https://en.wikipedia.org/wiki/Word_break_problem
"""


def backtrack(input_string: str, word_dict: set[str], start: int) -> bool:
"""
Helper function that uses backtracking to determine if a valid
word segmentation is possible starting from index 'start'.

Parameters:
input_string (str): The input string to be segmented.
word_dict (set[str]): A set of valid dictionary words.
start (int): The starting index of the substring to be checked.

Returns:
bool: True if a valid segmentation is possible, otherwise False.

Example:
>>> backtrack("leetcode", {"leet", "code"}, 0)
True

>>> backtrack("applepenapple", {"apple", "pen"}, 0)
True

>>> backtrack("catsandog", {"cats", "dog", "sand", "and", "cat"}, 0)
False
"""

# Base case: if the starting index has reached the end of the string
if start == len(input_string):
return True

# Try every possible substring from 'start' to 'end'
for end in range(start + 1, len(input_string) + 1):
if input_string[start:end] in word_dict and backtrack(
input_string, word_dict, end
):
return True

return False


def word_break(input_string: str, word_dict: set[str]) -> bool:
"""
Determines if the input string can be segmented into a sequence of
valid dictionary words using backtracking.

Parameters:
input_string (str): The input string to segment.
word_dict (set[str]): The set of valid words.

Returns:
bool: True if the string can be segmented into valid words, otherwise False.

Example:
>>> word_break("leetcode", {"leet", "code"})
True

>>> word_break("applepenapple", {"apple", "pen"})
True

>>> word_break("catsandog", {"cats", "dog", "sand", "and", "cat"})
False
"""

return backtrack(input_string, word_dict, 0)
4 changes: 2 additions & 2 deletions data_structures/linked_list/has_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ def __init__(self, data: Any) -> None:

def __iter__(self):
node = self
visited = []
visited = set()
while node:
if node in visited:
raise ContainsLoopError
visited.append(node)
visited.add(node)
yield node.data
node = node.next_node

Expand Down
60 changes: 46 additions & 14 deletions data_structures/stacks/next_greater_element.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,20 @@

def next_greatest_element_slow(arr: list[float]) -> list[float]:
"""
Get the Next Greatest Element (NGE) for all elements in a list.
Maximum element present after the current one which is also greater than the
current one.
Get the Next Greatest Element (NGE) for each element in the array
by checking all subsequent elements to find the next greater one.

This is a brute-force implementation, and it has a time complexity
of O(n^2), where n is the size of the array.

Args:
arr: List of numbers for which the NGE is calculated.

Returns:
List containing the next greatest elements. If no
greater element is found, -1 is placed in the result.

Example:
>>> next_greatest_element_slow(arr) == expect
True
"""
Expand All @@ -28,9 +39,21 @@ def next_greatest_element_slow(arr: list[float]) -> list[float]:

def next_greatest_element_fast(arr: list[float]) -> list[float]:
"""
Like next_greatest_element_slow() but changes the loops to use
enumerate() instead of range(len()) for the outer loop and
for in a slice of arr for the inner loop.
Find the Next Greatest Element (NGE) for each element in the array
using a more readable approach. This implementation utilizes
enumerate() for the outer loop and slicing for the inner loop.

While this improves readability over next_greatest_element_slow(),
it still has a time complexity of O(n^2).

Args:
arr: List of numbers for which the NGE is calculated.

Returns:
List containing the next greatest elements. If no
greater element is found, -1 is placed in the result.

Example:
>>> next_greatest_element_fast(arr) == expect
True
"""
Expand All @@ -47,14 +70,23 @@ def next_greatest_element_fast(arr: list[float]) -> list[float]:

def next_greatest_element(arr: list[float]) -> list[float]:
"""
Get the Next Greatest Element (NGE) for all elements in a list.
Maximum element present after the current one which is also greater than the
current one.

A naive way to solve this is to take two loops and check for the next bigger
number but that will make the time complexity as O(n^2). The better way to solve
this would be to use a stack to keep track of maximum number giving a linear time
solution.
Efficient solution to find the Next Greatest Element (NGE) for all elements
using a stack. The time complexity is reduced to O(n), making it suitable
for larger arrays.

The stack keeps track of elements for which the next greater element hasn't
been found yet. By iterating through the array in reverse (from the last
element to the first), the stack is used to efficiently determine the next
greatest element for each element.

Args:
arr: List of numbers for which the NGE is calculated.

Returns:
List containing the next greatest elements. If no
greater element is found, -1 is placed in the result.

Example:
>>> next_greatest_element(arr) == expect
True
"""
Expand Down
47 changes: 45 additions & 2 deletions dynamic_programming/floyd_warshall.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,58 @@ def __init__(self, n=0): # a graph with Node 0,1,...,N-1
] # dp[i][j] stores minimum distance from i to j

def add_edge(self, u, v, w):
"""
Adds a directed edge from node u
to node v with weight w.

>>> g = Graph(3)
>>> g.add_edge(0, 1, 5)
>>> g.dp[0][1]
5
"""
self.dp[u][v] = w

def floyd_warshall(self):
"""
Computes the shortest paths between all pairs of
nodes using the Floyd-Warshall algorithm.

>>> g = Graph(3)
>>> g.add_edge(0, 1, 1)
>>> g.add_edge(1, 2, 2)
>>> g.floyd_warshall()
>>> g.show_min(0, 2)
3
>>> g.show_min(2, 0)
inf
"""
for k in range(self.n):
for i in range(self.n):
for j in range(self.n):
self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j])

def show_min(self, u, v):
"""
Returns the minimum distance from node u to node v.

>>> g = Graph(3)
>>> g.add_edge(0, 1, 3)
>>> g.add_edge(1, 2, 4)
>>> g.floyd_warshall()
>>> g.show_min(0, 2)
7
>>> g.show_min(1, 0)
inf
"""
return self.dp[u][v]


if __name__ == "__main__":
import doctest

doctest.testmod()

# Example usage
graph = Graph(5)
graph.add_edge(0, 2, 9)
graph.add_edge(0, 4, 10)
Expand All @@ -38,5 +77,9 @@ def show_min(self, u, v):
graph.add_edge(4, 2, 4)
graph.add_edge(4, 3, 9)
graph.floyd_warshall()
graph.show_min(1, 4)
graph.show_min(0, 3)
print(
graph.show_min(1, 4)
) # Should output the minimum distance from node 1 to node 4
print(
graph.show_min(0, 3)
) # Should output the minimum distance from node 0 to node 3