Skip to content

Commit cefd1fd

Browse files
committed
some exercises
1 parent 50a912c commit cefd1fd

24 files changed

+1605
-1
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__pycache__/

README.md

Lines changed: 117 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,117 @@
1-
# coding_exercises
1+
This repository contains my implementation of useful data structures, algorithms,
2+
games, as well as my solutions to programming puzzles.
3+
4+
Each item is marked with a difficulty level.
5+
1 - easy
6+
2 - medium
7+
3 - hard
8+
9+
If a file name starts with 'lc', it's a problem from leetcode.com
10+
11+
Written in python3. Thanks Danijar Hafner ()
12+
13+
Data structures
14+
---------------
15+
16+
### Linked lists
17+
18+
- [x] List class (linked_list.py) - 1
19+
- [ ] Remove duplicates (linked_list_algos.py)
20+
- [ ] Find nth last element (linked_list_algos.py)
21+
- [ ] Remove node given only its object (linked_list_algos.py)
22+
- [ ] Sum linked lists with one digit per node (linked_list_algos.py)
23+
- [ ] Find beginning of circle (linked_list_algos.py)
24+
25+
### Trees
26+
27+
- [x] Binary heap class (binary_heap.py) - 2
28+
- [ ] Binary tree class (binary_tree.py) - 1
29+
- [x] Binary search tree class that allows duplicate values (binary_search_tree.py) - 2
30+
BST class inherits binary tree class
31+
- [ ] Red black tree class (red_black_tree.py)
32+
- [ ] B+ tree class (b_tree.py) - 3
33+
- [x] Trie class that allows word removal (trie.py) - 2
34+
- [x] Check if a binary tree is a binary search tree (binary_tree_algos.py) - 2
35+
- [ ] Check if a binary tree is balanced (binary_tree_algos.py)
36+
- [ ] Find first common ancestor of two nodes in a binary tree (binary_tree_algos.py)
37+
- [ ] Get all nodes of depth n in a binary tree (binary_tree_algos.py)
38+
- [ ] Given two large trees, check if the first is a subtree of the second (binary_tree_algos.py)
39+
- [ ] Find all sub paths in a binary tree that sum up to x (binary_tree_algos.py)
40+
- [ ] Create a balanced binary search tree from a sorted array (bst_algos.py)
41+
42+
### Graphs
43+
44+
- [ ] Undirected graph class
45+
- [ ] Directed graph class
46+
- [ ] Breadth first search (search.py)
47+
- [ ] Depth first search (search.py)
48+
- [ ] A-star (search.py)
49+
50+
### Stacks and queues
51+
52+
- [ ] Queue class (queue.py)
53+
- [x] Heap priority queue (priority_queue.py) - 1
54+
- [ ] Stack class (stack.py)
55+
- [ ] Stack that finds min in O(1) (min_stack.py)
56+
- [ ] Solve Hanoi towers using stacks (stack_algos.py)
57+
- [ ] Sort stack using only push, pop, peek and empty (stack_algos.py)
58+
- [ ] Build a queue using two stacks (stack_algos.py)
59+
60+
Algorithms
61+
----------
62+
63+
### Sorting
64+
- [x] Insertion sort (sort.py) - 1
65+
- [x] Selection sort (sort.py) - 1
66+
- [x] Merge sort (sort.py) - 2
67+
- [x] Heap sort (sort.py) - 2
68+
- [x] Quick sort (sort.py) - 2
69+
- [x] Counting sort (sort.py) - 2
70+
- [x] Radix sort (sort.py) - 2
71+
- [x] Bucket sort (sort.py) - 2
72+
73+
### Dynamic Programming
74+
- [ ] Computing a Fibonacci sequence
75+
- [ ] Find the longest common subsequence between two strings
76+
77+
### Recursion
78+
79+
- [ ] Find all permutations of a string
80+
- [ ] Find all subsets of a set
81+
- [ ] Find all proper combinations of n parentheses
82+
- [ ] Bucket fill
83+
- [ ] Check if it's possible to make a change with a set of coins
84+
- [ ] Check if it's possible to weight two objects with a set of weights
85+
- [ ] Eight queen
86+
87+
Programming Puzzles
88+
-------------------
89+
90+
### String Manipulation
91+
- [x] Check if two strings are anagrams in O(n + m) time (anagrams.py) - 1
92+
- [x] Find the longest palindromic substring in O(n^2) time (lc_longest_palindrome.py) - 2
93+
- [x] Check if a string has balanced delimiters in O(n) time (delim_balanced.py) - 2
94+
- [x] Reverse words while maintaining spaces and tabs in O(n) time (reverse_words.py) - 2
95+
- [x] Longest substring without repeating characters in O(n) time (lc_longest_nonrepeat_substring.py) - 2
96+
- [x] Longest contiguous substring of 2 distinct characters in O(n) time (substring_two_chars.py) - 2
97+
- [ ] Remove duplicate chars in a string
98+
- [ ] Encode and decode Caesar cipher (caesar.py)
99+
- [ ] Check if a string is a rotation of another
100+
101+
### Mathematical
102+
- [x] Reverse integers (lc_reverse_int.py) - 1
103+
- [x] Sieve of Eratosthenes (sieve_prime.py) - 1
104+
- [x] Two sum in O(n) time (lc_two_sum.py) - 1
105+
Given an array of integers, return indices of the two numbers
106+
such that they add up to a specific target.
107+
- [x] Year with maximum population (year_max_pop.py) - 1
108+
Given a list of people with their years of birth and death,
109+
find the year with max population
110+
- [x] FizzBuzz (fizzbuzz.py) - 1
111+
- [x] ZigZag conversion (lc_zigzag_convert.py) - 2
112+
- [x] Find sum of all subarrays of an array (subarray_sum.py) - 2
113+
- [x] Add two numbers, each represented by a reverse linked list (lc_add_number_reverse.py) - 2
114+
- [x] Find the median of two sorted arrays in O(log(m+n)) time (lc_median_arrays.py) - 3
115+
- [ ] Find nth smallest number that can be created using a list of prime factors
116+
- [ ] Count occurences of given digit in all numbers up to n
117+
- [ ] Rotate N x N matrix in place

anagrams.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
'''
2+
Two strings are said to be anagrams of one another if you can turn the first string into
3+
the second by rearranging its letters. For example, "table" and "bleat" are anagrams, as
4+
are "tear" and "rate." Your job is to write a function that takes in two strings as input and
5+
determines whether they're anagrams of one another.
6+
7+
Solution should run in O(n1 + n2)
8+
There are two solutions:
9+
one is using counter
10+
another one is also using dictionary, but slightly faster.
11+
'''
12+
from collections import Counter
13+
14+
def are_anagrams(str1, str2):
15+
if len(str1) != len(str2):
16+
return False
17+
dict1 = Counter(list(str1))
18+
dict2 = Counter(list(str2))
19+
for char in dict1:
20+
if not char in dict2 or dict2[char] != dict1[char]:
21+
return False
22+
return True
23+
24+
assert are_anagrams('table', 'bleat') == True
25+
assert are_anagrams('table', 'bleate') == False
26+
assert are_anagrams('honey', 'eyhon') == True
27+
assert are_anagrams('area', 'are') == False
28+
assert are_anagrams('', '') == True
29+
30+
def are_anagrams_fast(str1, str2):
31+
if len(str1) != len(str2):
32+
return False
33+
34+
char_dict = {}
35+
for char in str1:
36+
if not char in char_dict:
37+
char_dict[char] = 0
38+
char_dict[char] += 1
39+
40+
for char in str2:
41+
if char not in char_dict or char_dict[char] <= 0:
42+
return False
43+
char_dict[char] -= 1
44+
return True
45+
46+
assert are_anagrams_fast('table', 'bleat') == True
47+
assert are_anagrams_fast('table', 'bleate') == False
48+
assert are_anagrams_fast('honey', 'eyhon') == True
49+
assert are_anagrams_fast('area', 'are') == False
50+
assert are_anagrams_fast('', '') == True

binary_heap.py

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
'''
2+
A binary heap is a complete binary tree which satisfies the min-heap ordering property.
3+
The value of each node is greater than or equal to the value of its parent,
4+
with the minimum-value element at the root.
5+
6+
Methods available:
7+
insert(value): insert a value into the binary heap
8+
peek_min(): peek the next smallest value
9+
extract_min(): return the next smallest value and remove it from the heap.
10+
Raise ValueError if that value doesn't exist
11+
is_empty(): returns True if the heap is empty, False otherwise
12+
13+
Extra usage:
14+
iter(bh): return iteration to bh
15+
list(bh): list all values in the heap
16+
in a pre-order traversal (root, left, right)
17+
18+
BinaryHeap can be used to build a priority queue and to do heap sort algorithm
19+
20+
insert extract_min peek_min
21+
binary heap O(log n) O(log n) O(1)
22+
'''
23+
import random
24+
25+
class BinaryHeap(object):
26+
def __init__(self, arr=None):
27+
self._list = [0]
28+
if arr:
29+
for value in arr:
30+
self.insert(value)
31+
32+
def insert(self, value):
33+
self._list.append(value)
34+
self._bubble_up(len(self._list) - 1)
35+
36+
def peek_min(self):
37+
if len(self._list) == 1:
38+
raise ValueError('Empty')
39+
return self._list[1]
40+
41+
def extract_min(self):
42+
if len(self._list) == 1:
43+
raise ValueError('Empty')
44+
value = self._list[1]
45+
self._swap(1, -1)
46+
self._list = self._list[:-1]
47+
self._bubble_down(1)
48+
return value
49+
50+
def is_empty(self):
51+
return len(self._list) == 1
52+
53+
def __len__(self):
54+
return len(self._list) - 1
55+
56+
def __iter__(self):
57+
yield from iter(self._list[1:])
58+
59+
def _swap(self, idx1, idx2):
60+
temp = self._list[idx1]
61+
self._list[idx1] = self._list[idx2]
62+
self._list[idx2] = temp
63+
64+
def _bubble_down(self, idx):
65+
while 2 * idx < len(self._list): # has at least one child
66+
if len(self._list) == 2 * idx + 1:
67+
min_child = 2 * idx
68+
else:
69+
min_child = 2 * idx if self._list[2 * idx] < self._list[2 * idx + 1] else 2 * idx + 1
70+
self._swap(min_child, idx)
71+
idx = min_child
72+
73+
def _bubble_up(self, idx):
74+
parent = idx // 2
75+
while idx > 1 and self._list[idx] < self._list[parent]:
76+
self._swap(parent, idx)
77+
idx = parent
78+
parent = idx // 2
79+
80+
def test_heap():
81+
bh = BinaryHeap()
82+
values = random.sample(range(-15, 15), 30)
83+
for v in values:
84+
bh.insert(v)
85+
print(list(bh))
86+
87+
for v in iter(bh):
88+
print(v)
89+
90+
# test_heap()
91+

0 commit comments

Comments
 (0)