Skip to content

Commit 457cca4

Browse files
authored
Add files via upload
1 parent 864dbb8 commit 457cca4

24 files changed

+852
-0
lines changed

excel_id.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
"""Given a column number, return its alphabetical column id.
2+
For example, given 1, return "A". Given 27, return "AA"."""
3+
4+
5+
def return_id(num, char_set):
6+
"Function that return the column id of a given number."
7+
ans = ""
8+
while num:
9+
a = num % 26
10+
num //= 26
11+
ans += char_set[a - 1]
12+
return ans[::-1]
13+
14+
15+
charset = [chr(i) for i in range(65, 91)]
16+
n = 100000767
17+
print(return_id(n, charset))

execute_me_last.py

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"""---- Josephus Problem ----
2+
3+
There are N prisoners standing in a circle, waiting to be executed.
4+
The executions are carried out starting with the kth person,
5+
and removing every successive kth person going clockwise until there is no one left.
6+
7+
Given N and k, write an algorithm to determine where a prisoner should stand
8+
in order to be the last survivor.
9+
10+
For example, if N = 5 and k = 2, the order of executions would be [2, 4, 1, 5, 3],
11+
so you should return 3.
12+
13+
Bonus: Find an O(log N) solution if k = 2."""
14+
import math
15+
16+
17+
def last_man_standing(n, k):
18+
if n == 1:
19+
return 1
20+
21+
return (last_man_standing(n - 1, k) + (k-1)) % n + 1
22+
23+
24+
def last_man_standing_iteratively(n, k):
25+
p = 1
26+
for i in range(2, n + 1):
27+
p = (p + k - 1) % i + 1
28+
29+
return p
30+
31+
32+
def josephus_problem(n):
33+
"""Method to solve a special case when k = 2.
34+
The recurrence is given by:
35+
f(n) = 2f(n/2) + 1 ---- for n is even.
36+
f(n) = 2f(n-1 /2) + 1 ---- for n is odd.
37+
It is solvable by f(n) = 2L + 1 where L = n - 2 ^ floor(log n)."""
38+
39+
# if n == 1:
40+
# return 1
41+
#
42+
# return 2 * (n - 2 ** math.floor(math.log2(n))) + 1
43+
44+
p = 1
45+
for i in range(2, n + 1):
46+
p = 2 * (i - 2 ** math.floor(math.log2(i))) + 1
47+
48+
return p
49+
50+
51+
def most_significant_bit(n):
52+
a = 0
53+
while n != 1:
54+
n >>= 1
55+
a += 1
56+
return a
57+
58+
59+
def bitwise_jp_solution(n):
60+
"""X = n - 2^a
61+
ans = 2X + 1"""
62+
a = most_significant_bit(n)
63+
x = n ^ (1 << a)
64+
ans = (x << 1) | 1
65+
66+
return ans
67+
68+
69+
N = 500
70+
K = 2
71+
# print(last_man_standing(N, K))
72+
print(last_man_standing_iteratively(N, K))
73+
print(josephus_problem(N))
74+
print(bitwise_jp_solution(N))

game_strategy.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""You are asked to play the following game. You and an opponent take turns choosing either
2+
the first or last coin from the row, removing from the row, and receiving the value of the coin.
3+
4+
Write a program that returns the maximum amount of money you can win with certainty,
5+
if you move first, assuming your opponent plays optimally."""
6+
7+
8+
def optimal_strategy(arr):
9+
n = len(arr)
10+
table = [["-" for _ in range(n)]
11+
for _ in range(n)]
12+
13+
for spaces in range(n):
14+
for j in range(spaces, n):
15+
i = j - spaces
16+
17+
x, y, z = 0, 0, 0
18+
19+
if i + 2 <= j:
20+
x = table[i + 2][j]
21+
22+
if i + 1 <= j - 1:
23+
y = table[i + 1][j - 1]
24+
25+
if i <= j - 2:
26+
z = table[i][j - 2]
27+
28+
table[i][j] = max(arr[i] + min(x, y), arr[j] + min(y, z))
29+
30+
return table[0][n - 1]
31+
32+
33+
values = [8, 15, 7, 1]
34+
print(optimal_strategy(values))

longest_con_seq.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""Given an unsorted array of integers,
2+
find the length of the longest consecutive elements sequence.
3+
4+
For example, given [100, 4, 200, 1, 3, 2],
5+
the longest consecutive element sequence is [1, 2, 3, 4]. Return its length: 4.
6+
7+
Your algorithm should run in O(n) complexity.
8+
"""
9+
10+
11+
def lcs(arr):
12+
"""Function to return the longest consecutive sequence in the given array."""
13+
ans = 0
14+
s = set()
15+
16+
for i in arr:
17+
s.add(i)
18+
19+
for i in range(len(seq)):
20+
if arr[i] - 1 not in s:
21+
j = arr[i]
22+
23+
while j in s:
24+
j += 1
25+
26+
ans = max(ans, j - arr[i])
27+
28+
return ans
29+
30+
31+
seq = [100, 4, 200, 1, 3, 2]
32+
print("Longest consecutive sequence = ", lcs(seq))

longest_inc_seq.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""Given an array of numbers, find the length of the longest increasing subsequence in the array.
2+
The subsequence does not necessarily have to be contiguous.
3+
4+
For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15],
5+
the longest increasing subsequence has length 6: it is 0, 2, 6, 9, 11, 15."""
6+
7+
8+
def lis_v1(arr, n, max_len=1):
9+
"""Recursive function to find longest increasing subsequence in the given array."""
10+
max_end = 1
11+
12+
if n == 1:
13+
return 1
14+
15+
for i in range(1, n):
16+
res = lis_v1(arr, i, max_len)
17+
18+
if arr[i - 1] < arr[n - 1] and max_end < res + 1:
19+
max_end = res + 1
20+
21+
max_len = max(max_len, max_end)
22+
23+
return max_len
24+
25+
26+
def lis_v2(arr, n):
27+
"""Function based on Dynamic Programming to return longest increasing subsequence."""
28+
lis = [1] * n
29+
30+
for i in range(1, n):
31+
for j in range(0, i):
32+
if arr[i] > arr[j] and lis[i] < lis[j] + 1:
33+
lis[i] = lis[j] + 1
34+
35+
max_len = 0
36+
37+
for i in range(n):
38+
max_len = max(max_len, lis[i])
39+
40+
return max_len
41+
42+
43+
seq = [0, 1, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 10, 11, 15]
44+
print("Maximum increasing subsequence = ", lis_v2(seq, len(seq)))

make_it_large.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""Given a list of numbers, create an algorithm that arranges them
2+
in order to form the largest possible integer.
3+
For example, given [10, 7, 76, 415], you should return 77641510."""
4+
from functools import cmp_to_key as cmp_k
5+
6+
7+
def compare_it(a, b):
8+
new_a = int(str(a) + str(b))
9+
new_b = int(str(b) + str(a))
10+
11+
return new_a - new_b
12+
13+
14+
def largest_no(arr):
15+
x = [str(i) for i in sorted(arr, key=cmp_k(compare_it), reverse=True)]
16+
return "".join(x)
17+
18+
19+
def alternate_way(arr):
20+
n = len(str(max(arr)))
21+
extend_arr = [(str(i)*n, i) for i in arr]
22+
extend_arr.sort(reverse=True)
23+
return "".join([str(i[1]) for i in extend_arr])
24+
25+
26+
inp = [777, 0, 761, 4152]
27+
print(largest_no(inp))
28+
print(alternate_way(inp))

max_circular_sum.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""Given a circular array, compute its maximum subarray sum in O(n) time.
2+
3+
For example, given [8, -1, 3, 4], return 15 as we choose the numbers 3, 4,
4+
and 8 where the 8 is obtained from wrapping around."""
5+
6+
7+
def kadane_sum(arr):
8+
n = len(arr)
9+
max_sum = arr[0]
10+
max_curr = arr[0]
11+
12+
for i in range(1, n):
13+
max_curr = max(arr[i] + max_curr, arr[i])
14+
max_sum = max(max_sum, max_curr)
15+
16+
return max_sum
17+
18+
19+
def circular_sum(arr):
20+
max_kadane = kadane_sum(arr)
21+
max_wrap = 0
22+
23+
for i in range(len(arr)):
24+
max_wrap += arr[i]
25+
arr[i] = -arr[i]
26+
27+
max_wrap += kadane_sum(arr)
28+
29+
if max_kadane > max_wrap or not max_wrap:
30+
return max_kadane
31+
else:
32+
return max_wrap
33+
34+
35+
a = [-8, 2, -1, -5]
36+
print(circular_sum(a))

minimun_subset_sum.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
"""Given an array of positive integers, divide the array into two subsets such that
2+
the difference between the sum of the subsets is as small as possible.
3+
And return the difference.
4+
5+
For example, given [5, 10, 15, 20, 25], return the sets {10, 25} and {5, 15, 20},
6+
which has a difference of 5, which is the smallest possible difference"""
7+
import sys
8+
9+
10+
def find_min_recursive(arr, i, total_sum, first_sum):
11+
"""Recursive Solution"""
12+
if not i:
13+
return abs(total_sum - 2*first_sum)
14+
15+
return min(find_min_recursive(arr, i - 1, total_sum, first_sum + arr[i - 1]),
16+
find_min_recursive(arr, i - 1, total_sum, first_sum))
17+
18+
19+
def find_min(arr):
20+
n = len(arr)
21+
first_sum = 0
22+
23+
total_sum = sum(arr)
24+
25+
return find_min_recursive(arr, n, total_sum, first_sum)
26+
27+
28+
def dp_solution(arr):
29+
"""Solution using dynamic programming"""
30+
n = len(arr)
31+
sum_total = sum(arr)
32+
33+
dp = [[False for _ in range(sum_total//2 + 1)]
34+
for _ in range(n + 1)]
35+
36+
for i in range(n + 1):
37+
dp[i][0] = True
38+
39+
for i in range(1, n + 1):
40+
for j in range(1, sum_total//2 + 1):
41+
dp[i][j] = dp[i - 1][j]
42+
if arr[i - 1] <= j:
43+
dp[i][j] |= dp[i - 1][j - arr[i - 1]]
44+
45+
ans = sys.maxsize
46+
for j in range(sum_total // 2, -1, -1):
47+
if dp[n][j]:
48+
ans = sum_total - 2*j
49+
break
50+
51+
return ans
52+
53+
54+
a = [3, 7, 12, 15, 25, 45]
55+
# print(find_min(a))
56+
print(dp_solution(a))

no_same_please.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""Given a string with repeated characters, rearrange the string so that no two
2+
adjacent characters are the same. If this is not possible, return None.
3+
4+
For example, given "aaabbc", you could return "ababac". Given "aaab", return None."""
5+
from collections import defaultdict
6+
7+
8+
def no_same_char(string):
9+
ans = ""
10+
11+
store = defaultdict(int)
12+
for i in string:
13+
store[i] += 1
14+
15+
for j in store:
16+
if store[j]:
17+
if ans and j == ans[-1]:
18+
return None
19+
ans += j
20+
store[j] -= 1
21+
22+
return ans
23+
24+
25+
a = "aaab"
26+
print(no_same_char(a))

overlapping_intervals.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"""Given a list of possibly overlapping intervals,
2+
return a new list of intervals where all overlapping intervals have been merged."""
3+
4+
5+
class Intervals:
6+
"""class of intervals having start and end point."""
7+
def __init__(self, s=0, e=0):
8+
"""Initializer method for Intervals."""
9+
self.start = s
10+
self.end = e
11+
12+
def __repr__(self):
13+
"""Function to return a list with start and end points."""
14+
return "[{}, {}]".format(self.start, self.end)
15+
16+
17+
class Solution:
18+
"""class to find a overlapping intervals."""
19+
def merge(self, intervals):
20+
intervals = sorted(intervals, key=lambda x: x.start)
21+
out = []
22+
23+
for i in intervals:
24+
if out and i.start <= out[-1].end:
25+
out[-1].end = max(out[-1].end, i.end)
26+
else:
27+
out.append(i)
28+
29+
return out
30+
31+
32+
interval = [Intervals(1, 2), Intervals(6, 11), Intervals(0, 5), Intervals(7, 9), Intervals(1, 2)]
33+
print(Solution().merge(interval))

0 commit comments

Comments
 (0)