Skip to content
Open
44 changes: 44 additions & 0 deletions Algorithms/dijkstra.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import heapq

def dijkstra(graph, start):
"""
Dijkstra's algorithm to find shortest paths from start node to all other nodes.

Parameters:
graph : dict - adjacency list {node: [(neighbor, weight), ...]}
start : starting node

Returns:
distances : dict - shortest distance from start to each node
"""

distances = {node: float('inf') for node in graph}
distances[start] = 0

priority_queue = [(0, start)] # (distance, node)

while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)

if current_distance > distances[current_node]:
continue

for neighbor, weight in graph[current_node]:
distance = current_distance + weight

if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))

return distances

# Example usage:
if __name__ == "__main__":
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('A', 1), ('C', 2), ('D', 5)],
'C': [('A', 4), ('B', 2), ('D', 1)],
'D': [('B', 5), ('C', 1)]
}
start_node = 'A'
print("Shortest distances:", dijkstra(graph, start_node))
14 changes: 14 additions & 0 deletions Unique_Paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
dp ={}
def uniquePaths(m , n):
if n<1 or m<1:
return 0

if m==1 and n==1:
return 1

if (n,m) in dp:
return dp[(n,m)]

dp[(n,m)] = uniquePaths(m-1,n) + uniquePaths(m,n-1)

return dp[(n,m)]
Empty file added javascript/Bubblesort.js
Empty file.
49 changes: 49 additions & 0 deletions python/Bellman-FordAlgorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
def bellman_ford(vertex_count, edges, source):
dist = [float('inf')] * vertex_count
pred = [None] * vertex_count
dist[source] = 0
for _ in range(vertex_count - 1):
updated = False
for u, v, w in edges:
if dist[u] != float('inf') and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
updated = True
if not updated:
break
for u, v, w in edges:
if dist[u] != float('inf') and dist[u] + w < dist[v]:
return None, None
return dist, pred

def reconstruct_path(pred, target):
path = []
while target is not None:
path.append(target)
target = pred[target]
return path[::-1]

if __name__ == "__main__":
vertex_count = 5
edges = [
(0, 1, 6),
(0, 2, 7),
(1, 2, 8),
(1, 3, 5),
(1, 4, -4),
(2, 3, -3),
(2, 4, 9),
(3, 1, -2),
(4, 3, 7)
]
source = 0
dist, pred = bellman_ford(vertex_count, edges, source)
if dist is None:
print("Graph contains a negative-weight cycle")
else:
for v in range(vertex_count):
if dist[v] == float('inf'):
print(f"Vertex {v}: unreachable")
else:
path = reconstruct_path(pred, v)
print(f"Vertex {v}: distance = {dist[v]}, path = {path}")
Empty file added python/Coin_Change2.py
Empty file.
15 changes: 15 additions & 0 deletions python/Lonely Number Finder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
def find_lonely(nums):
from collections import Counter
count = Counter(nums)
lonely = []

for num in nums:
if count[num] == 1 and count[num - 1] == 0 and count[num + 1] == 0:
lonely.append(num)

return sorted(lonely)

# Example runs
print(find_lonely([10, 6, 5, 8])) # Output: [8, 10]
print(find_lonely([1, 3, 5, 3])) # Output: [1, 5]
print(find_lonely([7, 8, 9, 10])) # Output: []
25 changes: 25 additions & 0 deletions python/Longest_Alternating_Even_Odd_Subarray.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Longest_Alternating_Even_Odd_Subarray.py

def longestAlternatingEvenOdd(arr):
if not arr:
return 0

max_len = 1
curr_len = 1

for i in range(1, len(arr)):
# Check alternating condition:
if (arr[i] % 2) != (arr[i-1] % 2):
curr_len += 1
max_len = max(max_len, curr_len)
else:
curr_len = 1

return max_len


# Example usage:
if __name__ == "__main__":
nums = [3, 2, 5, 4, 7]
print("Input:", nums)
print("Longest Alternating Even-Odd Subarray Length:", longestAlternatingEvenOdd(nums))
Empty file.
12 changes: 12 additions & 0 deletions python/Mirror Index Sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def mirror_index_sum(nums):
total = 0
n = len(nums)
for i in range(n // 2 + n % 2):
if nums[i] == nums[n - 1 - i]:
total += nums[i]
return total

# Example runs
print(mirror_index_sum([1, 3, 2, 3, 1])) # Output: 5
print(mirror_index_sum([2, 5, 5, 2])) # Output: 4
print(mirror_index_sum([4, 1, 7, 9])) # Output: 0
Empty file added python/Save_People.py
Empty file.
19 changes: 19 additions & 0 deletions python/Sum_of_Unique_Elements.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Sum_of_Unique_Elements.py

def sumOfUnique(nums):
freq = {}
for n in nums:
freq[n] = freq.get(n, 0) + 1

total = 0
for key, val in freq.items():
if val == 1:
total += key
return total


# Example usage
if __name__ == "__main__":
arr = [1, 2, 3, 2]
print("Input:", arr)
print("Sum of Unique Elements:", sumOfUnique(arr))
Empty file added python/Unique_Paths.py
Empty file.
25 changes: 25 additions & 0 deletions python/knapsak.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
def fractional_knapsack(values, weights, max_capacity):
n = len(values)
items = [[values[i], weights[i]] for i in range(n)]
items.sort(key=lambda x: x[0] / x[1], reverse=True)

total_value = 0.0
remaining_capacity = max_capacity

for value, weight in items:
if weight <= remaining_capacity:
total_value += value
remaining_capacity -= weight
else:
total_value += (value / weight) * remaining_capacity
break

return total_value


if __name__ == "__main__":
values = [60, 100, 120]
weights = [10, 20, 30]
max_capacity = 50

print(fractional_knapsack(values, weights, max_capacity))