Skip to content

Commit db66b8c

Browse files
committed
mycompetitiveprogramming journey in python
1 parent a080d09 commit db66b8c

File tree

356 files changed

+16419
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

356 files changed

+16419
-0
lines changed

__init__.py

Whitespace-only changes.

alternatesequencesoppj.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
n=int(input())
2+
arr=list(map(int,input().split()))
3+
dp=[0 for i in range(n)]
4+
length=0
5+
for i in range(n):
6+
for j in range(n):
7+
if abs(arr[j])<abs(arr[i])and arr[i]*arr[j]<0:
8+
length=max(length,dp[j])
9+
dp[i]=length+1
10+
print(dp[n])

arrays/__init__.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from .delete_nth import *
2+
from .flatten import *
3+
from .garage import *
4+
from .josephus import *
5+
from .longest_non_repeat import *
6+
from .max_ones_index import *
7+
from .merge_intervals import *
8+
from .missing_ranges import *
9+
from .move_zeros import *
10+
from .plus_one import *
11+
from .rotate import *
12+
from .summarize_ranges import *
13+
from .three_sum import *
14+
from .trimmean import *
15+
from .top_1 import *
16+
from .two_sum import *
17+
from .limit import *
18+
from .n_sum import *

arrays/delete_nth.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
Given a list lst and a number N, create a new list
3+
that contains each number of the list at most N times without reordering.
4+
5+
For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2],
6+
drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3,
7+
which leads to [1,2,3,1,2,3]
8+
"""
9+
import collections
10+
11+
12+
# Time complexity O(n^2)
13+
def delete_nth_naive(array, n):
14+
ans = []
15+
for num in array:
16+
if ans.count(num) < n:
17+
ans.append(num)
18+
return ans
19+
20+
21+
# Time Complexity O(n), using hash tables.
22+
def delete_nth(array, n):
23+
result = []
24+
counts = collections.defaultdict(int) # keep track of occurrences
25+
26+
for i in array:
27+
28+
if counts[i] < n:
29+
result.append(i)
30+
counts[i] += 1
31+
32+
return result

arrays/flatten.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
Implement Flatten Arrays.
3+
Given an array that may contain nested arrays,
4+
produce a single resultant array.
5+
"""
6+
from collections.abc import Iterable
7+
8+
9+
# return list
10+
def flatten(input_arr, output_arr=None):
11+
if output_arr is None:
12+
output_arr = []
13+
for ele in input_arr:
14+
if isinstance(ele, Iterable):
15+
flatten(ele, output_arr) #tail-recursion
16+
else:
17+
output_arr.append(ele) #produce the result
18+
return output_arr
19+
20+
21+
# returns iterator
22+
def flatten_iter(iterable):
23+
"""
24+
Takes as input multi dimensional iterable and
25+
returns generator which produces one dimensional output.
26+
"""
27+
for element in iterable:
28+
if isinstance(element, Iterable):
29+
yield from flatten_iter(element)
30+
else:
31+
yield element

arrays/garage.py

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"""
2+
There is a parking lot with only one empty spot. Given the initial state
3+
of the parking lot and the final state. Each step we are only allowed to
4+
move a car
5+
out of its place and move it into the empty spot.
6+
The goal is to find out the least movement needed to rearrange
7+
the parking lot from the initial state to the final state.
8+
9+
Say the initial state is an array:
10+
11+
[1, 2, 3, 0, 4],
12+
where 1, 2, 3, 4 are different cars, and 0 is the empty spot.
13+
14+
And the final state is
15+
16+
[0, 3, 2, 1, 4].
17+
We can swap 1 with 0 in the initial array to get [0, 2, 3, 1, 4] and so on.
18+
Each step swap with 0 only.
19+
20+
Edit:
21+
Now also prints the sequence of changes in states.
22+
Output of this example :-
23+
24+
initial: [1, 2, 3, 0, 4]
25+
final: [0, 3, 2, 1, 4]
26+
Steps = 4
27+
Sequence :
28+
0 2 3 1 4
29+
2 0 3 1 4
30+
2 3 0 1 4
31+
0 3 2 1 4
32+
"""
33+
34+
35+
def garage(initial, final):
36+
37+
initial = initial[::] # prevent changes in original 'initial'
38+
seq = [] # list of each step in sequence
39+
steps = 0
40+
while initial != final:
41+
zero = initial.index(0)
42+
if zero != final.index(0): # if zero isn't where it should be,
43+
car_to_move = final[zero] # what should be where zero is,
44+
pos = initial.index(car_to_move) # and where is it?
45+
initial[zero], initial[pos] = initial[pos], initial[zero]
46+
else:
47+
for i in range(len(initial)):
48+
if initial[i] != final[i]:
49+
initial[zero], initial[i] = initial[i], initial[zero]
50+
break
51+
seq.append(initial[::])
52+
steps += 1
53+
54+
return steps, seq
55+
# e.g.: 4, [{0, 2, 3, 1, 4}, {2, 0, 3, 1, 4},
56+
# {2, 3, 0, 1, 4}, {0, 3, 2, 1, 4}]
57+
58+
"""
59+
thus:
60+
1 2 3 0 4 -- zero = 3, true, car_to_move = final[3] = 1,
61+
pos = initial.index(1) = 0, switched [0], [3]
62+
0 2 3 1 4 -- zero = 0, f, initial[1] != final[1], switched 0,1
63+
2 0 3 1 4 -- zero = 1, t, car_to_move = final[1] = 3,
64+
pos = initial.index(3) = 2, switched [1], [2]
65+
2 3 0 1 4 -- zero = 2, t, car_to_move = final[2] = 2,
66+
pos = initial.index(2) = 0, switched [0], [2]
67+
0 3 2 1 4 -- initial == final
68+
"""

arrays/josephus.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
"""
2+
There are people sitting in a circular fashion,
3+
print every third member while removing them,
4+
the next counter starts immediately after the member is removed.
5+
Print till all the members are exhausted.
6+
7+
For example:
8+
Input: consider 123456789 members sitting in a circular fashion,
9+
Output: 369485271
10+
"""
11+
12+
13+
def josephus(int_list, skip):
14+
skip = skip - 1 # list starts with 0 index
15+
idx = 0
16+
len_list = (len(int_list))
17+
while len_list > 0:
18+
idx = (skip + idx) % len_list # hash index to every 3rd
19+
yield int_list.pop(idx)
20+
len_list -= 1

arrays/limit.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
"""
2+
Sometimes you need to limit array result to use. Such as you only need the
3+
value over 10 or, you need value under than 100. By use this algorithms, you
4+
can limit your array to specific value
5+
6+
If array, Min, Max value was given, it returns array that contains values of
7+
given array which was larger than Min, and lower than Max. You need to give
8+
'unlimit' to use only Min or Max.
9+
10+
ex) limit([1,2,3,4,5], None, 3) = [1,2,3]
11+
12+
Complexity = O(n)
13+
"""
14+
15+
# tl:dr -- array slicing by value
16+
def limit(arr, min_lim=None, max_lim=None):
17+
min_check = lambda val: True if min_lim is None else (min_lim <= val)
18+
max_check = lambda val: True if max_lim is None else (val <= max_lim)
19+
20+
return [val for val in arr if min_check(val) and max_check(val)]

arrays/longest_non_repeat.py

+91
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
"""
2+
Given a string, find the length of the longest substring
3+
without repeating characters.
4+
5+
Examples:
6+
Given "abcabcbb", the answer is "abc", which the length is 3.
7+
Given "bbbbb", the answer is "b", with the length of 1.
8+
Given "pwwkew", the answer is "wke", with the length of 3.
9+
Note that the answer must be a substring,
10+
"pwke" is a subsequence and not a substring.
11+
"""
12+
13+
14+
def longest_non_repeat_v1(string):
15+
"""
16+
Find the length of the longest substring
17+
without repeating characters.
18+
"""
19+
if string is None:
20+
return 0
21+
dict = {}
22+
max_length = 0
23+
j = 0
24+
for i in range(len(string)):
25+
if string[i] in dict:
26+
j = max(dict[string[i]], j)
27+
dict[string[i]] = i + 1
28+
max_length = max(max_length, i - j + 1)
29+
return max_length
30+
31+
def longest_non_repeat_v2(string):
32+
"""
33+
Find the length of the longest substring
34+
without repeating characters.
35+
Uses alternative algorithm.
36+
"""
37+
if string is None:
38+
return 0
39+
start, max_len = 0, 0
40+
used_char = {}
41+
for index, char in enumerate(string):
42+
if char in used_char and start <= used_char[char]:
43+
start = used_char[char] + 1
44+
else:
45+
max_len = max(max_len, index - start + 1)
46+
used_char[char] = index
47+
return max_len
48+
49+
# get functions of above, returning the max_len and substring
50+
def get_longest_non_repeat_v1(string):
51+
"""
52+
Find the length of the longest substring
53+
without repeating characters.
54+
Return max_len and the substring as a tuple
55+
"""
56+
if string is None:
57+
return 0, ''
58+
sub_string = ''
59+
dict = {}
60+
max_length = 0
61+
j = 0
62+
for i in range(len(string)):
63+
if string[i] in dict:
64+
j = max(dict[string[i]], j)
65+
dict[string[i]] = i + 1
66+
if i - j + 1 > max_length:
67+
max_length = i - j + 1
68+
sub_string = string[j: i + 1]
69+
return max_length, sub_string
70+
71+
def get_longest_non_repeat_v2(string):
72+
"""
73+
Find the length of the longest substring
74+
without repeating characters.
75+
Uses alternative algorithm.
76+
Return max_len and the substring as a tuple
77+
"""
78+
if string is None:
79+
return 0, ''
80+
sub_string = ''
81+
start, max_len = 0, 0
82+
used_char = {}
83+
for index, char in enumerate(string):
84+
if char in used_char and start <= used_char[char]:
85+
start = used_char[char] + 1
86+
else:
87+
if index - start + 1 > max_len:
88+
max_len = index - start + 1
89+
sub_string = string[start: index + 1]
90+
used_char[char] = index
91+
return max_len, sub_string

arrays/max_ones_index.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
Find the index of 0 to be replaced with 1 to get
3+
longest continuous sequence
4+
of 1s in a binary array.
5+
Returns index of 0 to be
6+
replaced with 1 to get longest
7+
continuous sequence of 1s.
8+
If there is no 0 in array, then
9+
it returns -1.
10+
11+
e.g.
12+
let input array = [1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1]
13+
If we replace 0 at index 3 with 1, we get the longest continuous
14+
sequence of 1s in the array.
15+
So the function return => 3
16+
"""
17+
18+
19+
def max_ones_index(arr):
20+
21+
n = len(arr)
22+
max_count = 0
23+
max_index = 0
24+
prev_zero = -1
25+
prev_prev_zero = -1
26+
27+
for curr in range(n):
28+
29+
# If current element is 0,
30+
# then calculate the difference
31+
# between curr and prev_prev_zero
32+
if arr[curr] == 0:
33+
if curr - prev_prev_zero > max_count:
34+
max_count = curr - prev_prev_zero
35+
max_index = prev_zero
36+
37+
prev_prev_zero = prev_zero
38+
prev_zero = curr
39+
40+
if n - prev_prev_zero > max_count:
41+
max_index = prev_zero
42+
43+
return max_index

0 commit comments

Comments
 (0)