GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Added more DP solutions · onowdev/coding-problems@3cb8c86

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • Dynamic Programming
    • longest_common_subsequence.py
    • longest_common_substring.py
    • longest_increasing_subsequence.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎Dynamic Programming/longest_common_subsequence.py‎

Copy file name to clipboard
+75Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
'''
2+
Longest Common Subsequence
3+
4+
Given 2 strings, find the longest common subseqence - https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
5+
NOT Longest Common Substring, this is a different problem.
6+
Substring is a string composed ONLY of neighboring chars, subsequence could contain non-neighboring chars.
7+
8+
Input: 'ABAZDC', 'BACBAD'
9+
Output: 'ABAD'
10+
11+
Input: 'I'm meto', 'I am Meto'
12+
Output: 'Im eto'
13+
14+
=========================================
15+
Dynamic programming solution.
16+
Find more details here: https://www.geeksforgeeks.org/printing-longest-common-subsequence/
17+
Time Complexity: O(N * M)
18+
Space Complexity: O(N * M) , can be O(M) see longest_common_substring.py solution (but you'll need to save subsequences)
19+
'''
20+
21+
22+
############
23+
# Solution #
24+
############
25+
26+
def longest_common_subsequence(str1, str2):
27+
n, m = len(str1), len(str2)
28+
# create dp matrix
29+
dp = [[0 for j in range(m + 1)] for i in range(n + 1)]
30+
31+
# run dp
32+
for i in range(1, n + 1):
33+
for j in range(1, m + 1):
34+
# checks only in 3 directions in the table
35+
# in short: to the current position dp could come from those 3 previous positions
36+
# ^ ^
37+
# \ |
38+
# <- O
39+
if str1[i - 1] == str2[j - 1]:
40+
# from this position dp could come only if there is a match in the previous chars
41+
dp[i][j] = dp[i - 1][j - 1] + 1
42+
else:
43+
# dp could come from these positions only if there is no much
44+
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
45+
46+
# find the subseqence/string
47+
result = ''
48+
i = n
49+
j = m
50+
51+
while (i != 0) and (j != 0):
52+
# use the inverse logic from upper code (filling the dp table)
53+
if str1[i - 1] == str2[j - 1]:
54+
result = str1[i - 1] + result
55+
j -= 1
56+
i -= 1
57+
elif dp[i - 1][j] < dp[i][j - 1]:
58+
j -= 1
59+
else:
60+
i -= 1
61+
62+
return result
63+
64+
65+
###########
66+
# Testing #
67+
###########
68+
69+
# Test 1
70+
# Correct result => 'ABAD'
71+
print(longest_common_subsequence('ABAZDC', 'BACBAD'))
72+
73+
# Test 2
74+
# Correct result => 'Im eto'
75+
print(longest_common_subsequence('I\'m meto', 'I am Meto'))
Collapse file

‎Dynamic Programming/longest_common_substring.py‎

Copy file name to clipboard
+65Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
'''
2+
Longest Common Substring
3+
4+
Given two strings X and Y, find the of longest common substring.
5+
6+
Input: 'GeeksforGeeks', 'GeeksQuiz'
7+
Output: 'Geeks'
8+
9+
=========================================
10+
Dynamic Programming Solution.
11+
Time Complexity: O(N * M)
12+
Space Complexity: O(M)
13+
* There is a faster solution, using Suffix tree, Time Complexity O(N + M).
14+
'''
15+
16+
17+
############
18+
# Solution #
19+
############
20+
21+
def longest_common_substring(str1, str2):
22+
n, m = len(str1), len(str2)
23+
# instead of creating a whole dp table, use only 2 rows (current and previous row)
24+
curr = [0 for j in range(m + 1)]
25+
prev = []
26+
max_length = 0
27+
max_idx = 0
28+
29+
for i in range(1, n + 1):
30+
# save the previous row and create the current row
31+
prev = curr
32+
curr = [0 for j in range(m + 1)]
33+
34+
for j in range(1, m + 1):
35+
if str1[i - 1] == str2[j - 1]:
36+
# search only for matching chars
37+
curr[j] = prev[j - 1] + 1
38+
39+
if curr[j] > max_length:
40+
# save the last matching index of the first string
41+
max_length = curr[j]
42+
max_idx = i
43+
44+
return str1[max_idx - max_length: max_idx]
45+
46+
47+
###########
48+
# Testing #
49+
###########
50+
51+
# Test 1
52+
# Correct result => BABC
53+
print(longest_common_substring('ABABC', 'BABCA'))
54+
55+
# Test 2
56+
# Correct result => Geeks
57+
print(longest_common_substring('GeeksforGeeks', 'GeeksQuiz'))
58+
59+
# Test 3
60+
# Correct result => abcd
61+
print(longest_common_substring('abcdxyz', 'xyzabcd'))
62+
63+
# Test 4
64+
# Correct result => abcdez
65+
print(longest_common_substring('zxabcdezy', 'yzabcdezx'))
Collapse file

‎Dynamic Programming/longest_increasing_subsequence.py‎

Copy file name to clipboard
+136Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
'''
2+
Longest Increasing Subsequence (LIS)
3+
4+
Find the longest increasing subsequence.
5+
(subsequence doesn't mean that all elements need to be neighboring in the original array).
6+
7+
Sample input: [1, 4, 2, 0, 3, 1]
8+
Sample output: [1, 2, 3]
9+
or output the length
10+
Sample output: 3
11+
12+
=========================================
13+
Dynamic programming (classical) solution.
14+
Time Complexity: O(N^2)
15+
Space Complexity: O(N)
16+
Dynamic programing in combination with binary search.
17+
Explanation in details: https://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/
18+
Time Complexity: O(N * logN)
19+
Space Complexity: O(N^2) , if you need only the length of the LIS, extra space complexity will be O(N)
20+
'''
21+
22+
23+
##############
24+
# Solution 1 #
25+
##############
26+
27+
def longest_increasing_subsequence_1(nums):
28+
n = len(nums)
29+
if n == 0:
30+
return 0
31+
dp = [1 for i in range(n)]
32+
max_val = 1
33+
34+
# run dp
35+
for i in range(n):
36+
for j in range(i):
37+
if nums[j] < nums[i]:
38+
dp[i] = max(dp[i], dp[j] + 1)
39+
max_val = max(max_val, dp[i])
40+
41+
# find the values (there could be more combinations/solutions)
42+
current_val = max_val
43+
result = [0 for i in range(current_val)]
44+
# start from the back and look for the biggest value in dp list
45+
for i in range(n - 1, -1, -1):
46+
if (dp[i] == current_val) and ((len(result) == current_val) or (result[current_val] > nums[i])):
47+
current_val -= 1
48+
result[current_val] = nums[i]
49+
50+
return result
51+
52+
53+
##############
54+
# Solution 2 #
55+
##############
56+
57+
def longest_increasing_subsequence_2(nums):
58+
n = len(nums)
59+
if n == 0:
60+
return 0
61+
# the last dp array result in longest increasing subsequence
62+
dp = []
63+
64+
for i in range(n):
65+
idx = binary_search(dp, nums[i])
66+
k = len(dp)
67+
68+
if idx == k:
69+
# bigger element than the current wasn't found
70+
arr = []
71+
if k != 0:
72+
arr = [i for i in dp[-1]] # make a copy
73+
arr.append(nums[i])
74+
75+
dp.append(arr)
76+
elif dp[idx][-1] > nums[i]:
77+
# smaller element was found, replace it
78+
dp[idx][-1] = nums[i]
79+
80+
return dp[-1]
81+
82+
def binary_search(dp, target):
83+
l = 0
84+
r = len(dp) - 1
85+
86+
while l <= r:
87+
mid = l + (r - l) // 2
88+
if dp[mid][-1] == target:
89+
return mid
90+
elif dp[mid][-1] < target:
91+
l = mid + 1
92+
else:
93+
r = mid - 1
94+
95+
return l
96+
97+
98+
###########
99+
# Testing #
100+
###########
101+
102+
# Test 1
103+
# Correct result => [2, 3, 7, 18] - one of the possible combinations
104+
arr = [10, 9, 2, 5, 3, 7, 101, 18]
105+
print(longest_increasing_subsequence_1(arr))
106+
print(longest_increasing_subsequence_2(arr))
107+
108+
# Test 2
109+
# Correct result => [1, 2, 3]
110+
arr = [1, 2, 3]
111+
print(longest_increasing_subsequence_1(arr))
112+
print(longest_increasing_subsequence_2(arr))
113+
114+
# Test 3
115+
# Correct result => [1, 2, 5, 7, 12] - one of the possible combinations
116+
arr = [10, 1, 3, 8, 2, 0, 5, 7, 12, 3]
117+
print(longest_increasing_subsequence_1(arr))
118+
print(longest_increasing_subsequence_2(arr))
119+
120+
# Test 4
121+
# Correct result => [1, 2, 3, 4, 5, 6]
122+
arr = [12, 1, 11, 2, 10, 3, 9, 4, 8, 5, 7, 6]
123+
print(longest_increasing_subsequence_1(arr))
124+
print(longest_increasing_subsequence_2(arr))
125+
126+
# Test 5
127+
# Correct result => [1, 2, 3]
128+
arr = [1, 4, 2, 0, 3, 1]
129+
print(longest_increasing_subsequence_1(arr))
130+
print(longest_increasing_subsequence_2(arr))
131+
132+
# Test 6
133+
# Correct result => [3] - one of the possible combinations
134+
arr = [7, 5, 5, 5, 5, 5, 3]
135+
print(longest_increasing_subsequence_1(arr))
136+
print(longest_increasing_subsequence_2(arr))

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.