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 new solutions · onowdev/coding-problems@598e135

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • Dynamic Programming
    • sum_non-adjecent.py
    • transform_number_ascending_digits.py
    • word_break.py
  • Lists
    • container_with_most_water.py
    • trapped_watter.py
  • Math
    • sum_of_multiples.py
    • unique_paths.py
  • Other
    • valid_parentheses.py
  • README.md
  • Strings
    • swap_first_and_last_word.py
  • Trees
    • unival_trees.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎Dynamic Programming/sum_non-adjecent.py‎

Copy file name to clipboard
+92Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
'''
2+
Sum of non-adjacent numbers
3+
4+
Given a list of integers, write a function that returns the largest sum of non-adjacent numbers.
5+
Numbers can be 0 or negative.
6+
7+
Input: [2, 4, 6, 2, 5]
8+
Output: 13
9+
Output explanation: We pick 2, 6, and 5.
10+
11+
Input: [5, 1, 1, 5]
12+
Output: 10
13+
Output explanation: We pick 5 and 5.
14+
15+
=========================================
16+
Dynamic programming solution, but don't need the whole DP array, only the last 3 sums (DPs) are needed.
17+
Time Complexity: O(N)
18+
Space Complexity: O(1)
19+
'''
20+
21+
22+
############
23+
# Solution #
24+
############
25+
26+
def sum_non_adjacent(arr):
27+
n = len(arr)
28+
# from the dp matrix you only need the last 3 sums
29+
sums = [0, 0, 0]
30+
31+
# TODO: refactor these if-elses, those are to skip using of DP matrix
32+
if n == 0:
33+
return 0
34+
35+
# if negative or zero, the sum will be 0
36+
sums[0] = max(arr[0], 0)
37+
38+
if n == 1:
39+
return sums[0]
40+
41+
sums[1] = arr[1]
42+
# if the second number is negative or zero, then jump it
43+
if sums[1] <= 0:
44+
sums[1] = sums[0]
45+
46+
if n == 2:
47+
return max(sums[0], sums[1])
48+
49+
sums[2] = arr[2]
50+
# if the third number is negative or zero, then jump it
51+
if sums[2] <= 0:
52+
sums[2] = max(sums[0], sums[1])
53+
else:
54+
sums[2] += sums[0]
55+
56+
# THE SOLUTION
57+
for i in range(3, n):
58+
temp = 0
59+
60+
if arr[i] > 0:
61+
# take this number, because it's positive and the sum will be bigger
62+
temp = max(sums[0], sums[1]) + arr[i]
63+
else:
64+
# don't take this number, because the sum will be same or smaller
65+
temp = max(sums)
66+
67+
# remove the first sum
68+
sums = sums[1:] + [temp]
69+
70+
# return the max sum
71+
return max(sums)
72+
73+
74+
###########
75+
# Testing #
76+
###########
77+
78+
# Test 1
79+
# Correct result => 13
80+
print(sum_non_adjacent([2, 4, 6, 2, 5]))
81+
82+
# Test 2
83+
# Correct result => 15
84+
print(sum_non_adjacent([2, 4, 2, 6, 2, -3, -2, 0, -3, 5]))
85+
86+
# Test 3
87+
# Correct result => 10
88+
print(sum_non_adjacent([5, 1, 1, 5]))
89+
90+
# Test 4
91+
# Correct result => 10
92+
print(sum_non_adjacent([5, 1, -1, 1, 5]))
Collapse file

‎Dynamic Programming/transform_number_ascending_digits.py‎

Copy file name to clipboard
+57Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
'''
2+
Transform Number Ascending Digits
3+
4+
Given a number and we need to transform to a new number where all its digits are ordered in a non descending order.
5+
All digits can be increased, decreased, over/underflow are allowed.
6+
Find the minimum number of operations we need to do to create a new number with its ordered digits.
7+
8+
Input: '5982'
9+
Output: 4
10+
Output explanation: 5999, 1 operation to transform 8 to 9, 3 operations to transform 2 to 9.
11+
12+
=========================================
13+
Dynamic programming solution.
14+
Time Complexity: O(N) , O(N * 10 * 10) = O(100 N) = O(N)
15+
Space Complexity: O(1) , O(10 * 10) = O(100) = O(1)
16+
'''
17+
18+
19+
############
20+
# Solution #
21+
############
22+
23+
def operations(number):
24+
n = len(number)
25+
diff = lambda i, j: abs(j - int(number[i]))
26+
# compute diff between the current digit and wanted digit, and fill the dp
27+
prev_dp = [min(diff(0, i), 10 - diff(0, i)) for i in range(10)]
28+
29+
# go through all digits and see all possible combinations using dynamic programming
30+
for i in range(1, n):
31+
curr_dp = [min(diff(i, j), 10 - diff(i, j)) for j in range(10)]
32+
for j in range(10):
33+
# find the min value for the previous digit and add it to the current value
34+
curr_dp[j] += min(prev_dp[0 : j + 1])
35+
prev_dp = curr_dp
36+
37+
# min value from the last digit
38+
min_dist = min(prev_dp)
39+
40+
return min_dist
41+
42+
43+
###########
44+
# Testing #
45+
###########
46+
47+
# Test 1
48+
# Correct result => 1
49+
print(operations('901'))
50+
51+
# Test 2
52+
# Correct result => 3
53+
print(operations('301'))
54+
55+
# Test 3
56+
# Correct result => 4
57+
print(operations('5982'))
Collapse file

‎Dynamic Programming/word_break.py‎

Copy file name to clipboardExpand all lines: Dynamic Programming/word_break.py
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
Space Complexity: O(N+W) , W = number of words
1818
Bonus solution: Backtracking, iterate the sentence construct a substring and check if that substring exist in the set of words.
1919
If the end is reached but the last word doesn't exist in the words, go back 1 word from the result (backtracking).
20+
* But this solution doesn't give the result with the least number of words (gives the first found result)
2021
Time Complexity: O(?) , (worst case, about O(W! * N), for example sentence='aaaaaac', words=['a','aa','aaa','aaaa','aaaaa', 'aaaaaa'])
2122
Space Complexity: O(W)
2223
'''
Collapse file

‎Lists/container_with_most_water.py‎

Copy file name to clipboardExpand all lines: Lists/container_with_most_water.py
+4-1Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
'''
22
Container With Most Water
33
4-
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
4+
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).
5+
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
6+
Find two lines, which together with x-axis forms a container, such that the container contains the most water.
57
68
Input: [1,8,6,2,5,4,8,3,7]
79
Output: 49
@@ -44,5 +46,6 @@ def max_area(height):
4446
# Testing #
4547
###########
4648

49+
# Test 1
4750
# Correct result => 49
4851
print(max_area([1, 8, 6, 2, 5, 4, 8, 3, 7]))
Collapse file

‎Lists/trapped_watter.py‎

Copy file name to clipboard
+66Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
'''
2+
Trapped Water
3+
4+
You are given an array of non-negative integers that represents a two-dimensional elevation map where each element is unit-width wall and the integer is the height.
5+
Suppose it will rain and all spots between two walls get filled up.
6+
Compute how many units of water remain trapped on the map in O(N) time and O(1) space.
7+
8+
Input: [2, 1, 2]
9+
Output: 1
10+
Output explanation: We can hold 1 unit of water in the middle.
11+
12+
Input: [3, 0, 1, 3, 0, 5]
13+
Output: 8
14+
Output explanation: We can hold 3 units in the first index, 2 in the second, and 3 in the fourth index (we cannot hold 5 since it would run off to the left), so we can trap 8 units of water.
15+
16+
=========================================
17+
First search for the max wall from front, after that correct the left water starting from the back side
18+
Time Complexity: O(N)
19+
Space Complexity: O(1)
20+
'''
21+
22+
23+
############
24+
# Solution #
25+
############
26+
27+
def trapped_water(elevation_map):
28+
n = len(elevation_map)
29+
water = 0
30+
31+
# start from front of the array
32+
# and look for the max wall
33+
last_idx = 0
34+
max_height = elevation_map[0]
35+
36+
for i in range(1, n):
37+
if elevation_map[i] >= max_height:
38+
last_idx = i # save the highest wall index for later
39+
max_height = elevation_map[i]
40+
41+
water += max_height - elevation_map[i]
42+
43+
# after that start from back and go reverse to the max wall
44+
# and correct the result (pour the extra water if there is smaller wall on the right side)
45+
back_max_height = elevation_map[-1]
46+
47+
for i in reversed(range(last_idx + 1, n - 1)):
48+
if elevation_map[i] > back_max_height:
49+
back_max_height = elevation_map[i]
50+
51+
water -= max_height - back_max_height
52+
53+
return water
54+
55+
56+
###########
57+
# Testing #
58+
###########
59+
60+
# Test 1
61+
# Correct result => 1
62+
print(trapped_water([2, 1, 2]))
63+
64+
# Test 2
65+
# Correct result => 8
66+
print(trapped_water([3, 0, 1, 3, 0, 5]))
Collapse file

‎Math/sum_of_multiples.py‎

Copy file name to clipboard
+41Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
Multiples of a OR b
3+
4+
If we list all the natural numbers below 10 that are multiples of 3 OR 5, we get 3, 5, 6 and 9.
5+
The sum of these multiples is 23.
6+
Find the sum of all the multiples of A or B below N.
7+
8+
=========================================
9+
Don't need iteration to solve this problem, you need to find only how many divisors are there.
10+
Example - 3 + 6 + 9 ... + N = (1 + 2 + 3 + ... N // 3) * 3
11+
Sum(K)*N = 1*N + 2*N + ... + (K-1)*N + K*N
12+
Use sum formula - (N * (N + 1))/2
13+
Time Complexity: O(1)
14+
Space Complexity: O(1)
15+
'''
16+
17+
############
18+
# Solution #
19+
############
20+
21+
def sum_of_multiples_below(a, b, total):
22+
total -= 1
23+
# sum of dividens of A + sum of dividens of B - sum of common dividens (because they're added twice)
24+
return sum_of_dividends(total, a) + sum_of_dividends(total, b) - sum_of_dividends(total, a * b)
25+
26+
def sum_of_dividends(total, divisor):
27+
n = total // divisor
28+
return (n * (n + 1) // 2) * divisor
29+
30+
31+
###########
32+
# TESTING #
33+
###########
34+
35+
# Test 1
36+
# Correct result => 23
37+
print(sum_of_multiples_below(3, 5, 10))
38+
39+
# Test 2
40+
# Correct result => 233168
41+
print(sum_of_multiples_below(3, 5, 1000))
Collapse file

‎Math/unique_paths.py‎

Copy file name to clipboard
+68Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
'''
2+
Unique Paths
3+
4+
Find the unique paths in a matrix starting from the upper left corner and ending in the bottom right corner.
5+
6+
=========================================
7+
Dynamic programming (looking from the left and up neighbour), but this is a slower solution, see the next one.
8+
Time Complexity: O(N*M)
9+
Space Complexity: O(N*M)
10+
The DP table is creating an Pascal Triangle, so this problem can be easily solved by using the combinatorial formula!
11+
Much faster and doesn't use extra space.
12+
Time Complexity: O(min(M, N))
13+
Space Complexity: O(1)
14+
'''
15+
16+
################################
17+
# Solution Dynamic Programming #
18+
################################
19+
20+
def unique_paths_dp(n, m):
21+
# all values at i=0 should be 1 (the rest are not important, they'll be computed later)
22+
dp = [[1 for j in range(m)] for i in range(n)]
23+
24+
# calculate only inner values
25+
for i in range(1, n):
26+
for j in range(1, m):
27+
dp[i][j] = dp[i][j - 1] + dp[i - 1][j]
28+
29+
return dp[n-1][m-1]
30+
31+
32+
#################################
33+
# Solution Combinations Formula #
34+
#################################
35+
36+
def unique_paths(n, m):
37+
m, n = min(m, n), max(m, n)
38+
lvl = m + n - 2
39+
pos = m - 1
40+
comb = 1
41+
42+
# combinations formula C(N, R) = N! / R! * (N - R)!
43+
for i in range(1, pos + 1):
44+
comb *= lvl
45+
comb /= i
46+
lvl -= 1
47+
48+
return int(comb + 0.001) # 0.001 just in case because of overflow
49+
50+
51+
###########
52+
# Testing #
53+
###########
54+
55+
# Test 1
56+
# Correct result => 924
57+
print(unique_paths(7, 7))
58+
print(unique_paths_dp(7, 7))
59+
60+
# Test 2
61+
# Correct result => 28
62+
print(unique_paths(7, 3))
63+
print(unique_paths_dp(7, 3))
64+
65+
# Test 3
66+
# Correct result => 28
67+
print(unique_paths(3, 7))
68+
print(unique_paths_dp(3, 7))

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.