├── chapter4 └── count_bits.py ├── Chapter4 └── 476NumberComplement.java ├── Chapter7 └── 7.1Merge two sorted lists.py ├── Chapter5 └── 5.3 Multiply two arbitrary-precision integers.py ├── Chapter12 └── 12.9 Find the longest subarray with distinct entries.py └── README.md /chapter4/count_bits.py: -------------------------------------------------------------------------------- 1 | def count_bits(x): 2 | num_bits = 0 3 | while bool(x): 4 | num_bits += x + 1 #num_bits = num_bits + 1 5 | x >>= 1 6 | return num_bits 7 | -------------------------------------------------------------------------------- /Chapter4/476NumberComplement.java: -------------------------------------------------------------------------------- 1 | //This is a problem from Leetcode, no 476 2 | 3 | /* 4 | Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. 5 | 6 | Note: 7 | The given integer is guaranteed to fit within the range of a 32-bit signed integer. 8 | You could assume no leading zero bit in the integer’s binary representation. 9 | */ 10 | 11 | //example: input = 5, out = 2 12 | 13 | public class NumberComplement{ 14 | public static int findComplement(int num){ 15 | int n = 0; 16 | 17 | while (n < num) { 18 | n = (n << 1) | 1; 19 | } 20 | return n - num; 21 | } 22 | 23 | public static void main(String[] args){ 24 | long fc = findComplement(5); 25 | System.out.println(fc); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Chapter7/7.1Merge two sorted lists.py: -------------------------------------------------------------------------------- 1 | #define the new class for ListNode 2 | class ListNode: 3 | def __init__(self, data=0, next_node=None): 4 | self.data = data 5 | self.next = next_node 6 | def __repr__(self): 7 | return '%s -> %s' % (self.data, self.next) 8 | 9 | 10 | # convert lst to a linked list, and return that 11 | def genList(lst): 12 | R = None 13 | for i in range(len(lst)-1, -1, -1): 14 | R = ListNode(lst[i], R) 15 | return R 16 | 17 | # combining two linked list into one 18 | def combine(L1, L2): 19 | dummy_head = tail = ListNode() 20 | while L1 and L2: 21 | if L1.data < L2.data: 22 | tail.next, L1 = L1, L1.next 23 | else: 24 | tail.next, L2 = L2, L2.next 25 | tail = tail.next 26 | tail.next = L1 or L2 27 | return dummy_head.next 28 | 29 | def main(): 30 | L1 = genList([1, 5]) 31 | L2 = genList([4]) 32 | print(L1) 33 | print(L2) 34 | LR = combine(L1, L2) 35 | print(LR) 36 | 37 | 38 | if __name__ == "__main__": 39 | main() 40 | 41 | -------------------------------------------------------------------------------- /Chapter5/5.3 Multiply two arbitrary-precision integers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Two numbers are represented in two arrays (lists in python) 3 | A few things to note: 4 | 1. there is signs of the number to take care of 5 | 2. unnecessary 0's in front should be taken care of, e.g. [0,0,1,2] should be [1,2] 6 | 3. in order to save space, we can incrementally add the terms rather than compute all of them individually and add up 7 | 4. when multiplying two numbers with n digits and m digits, the max digits of the new number is n+m 8 | 9 | The time complexity of the following algorithm is O(nm) with O(1) space complexity. 10 | """ 11 | 12 | 13 | def mul_two(x, y): 14 | # take care of the signs of the first number 15 | sign = -1 if (x[0] < 0) ^ (y[0] < 0) else 1 16 | x[0], y[0] = abs(x[0]), abs(y[0]) 17 | 18 | # initialize an array for all the digits 19 | result = [0] * (len(x) + len(y)) 20 | for i in reversed(range(len(x))): 21 | for j in reversed(range(len(y))): 22 | result[i + j + 1] += x[i] * y[j] 23 | result[i + j] += result[i + j + 1]//10 24 | result[i + j + 1] %= 10 25 | 26 | # removing 0's 27 | result = result[next((i for i, x in enumerate(result) if x != 0), len(result)):] or [0] 28 | 29 | # adding the sign 30 | return [sign*result[0]] + result[1:] 31 | def main(): 32 | assert mul_two([0], [1,2]) == [0] 33 | assert mul_two([1,3], [3]) == [3,9] 34 | 35 | if __name__ == '__main__': 36 | main() 37 | -------------------------------------------------------------------------------- /Chapter12/12.9 Find the longest subarray with distinct entries.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem 12.9 Find the longest subarray with distinct entries 3 | 4 | Items to keep track of: 5 | 1. the length of the longest subarray so far: max_len 6 | 2. the start of the longest subarray (or potentially longest): start 7 | 3. letter we have seen so far: used = {} 8 | 9 | when we see a letter in the string one of the following situations can happen: 10 | 1. it's not in the used{} - todo: add it into used{}, and add 1 to max_len 11 | 2. it's in the used{} and the current start position is smaller or equal to this letter - todo: we discard all the 12 | substring before and update the start to the new position, which is a start for a potentially longer substring 13 | 3. it's in the used{} but the current start position is greater than the first occurrence of this letter so we don't 14 | need to update the start position again 15 | 16 | in addition, for every letter we see, we update its index in the dictionary, i.e. if we haven't seen it, we will add it; 17 | if we saw it before, we will update the index to the new position of the same letter. 18 | """ 19 | 20 | def longest_sub(S): 21 | max_len, start = 0, 0 22 | used = {} 23 | for i, e in enumerate(S): 24 | if e in used and start <= used[e]: 25 | start = used[e] +1 26 | else: 27 | max_len = max(max_len, i - start+1) 28 | used[e] = i 29 | return max_len 30 | 31 | def main(): 32 | S1 = "aaabcdaafhb" 33 | S2 = "tmmzuxt" 34 | print(longest_sub(S2)) 35 | if __name__ == "__main__": 36 | main() 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ElementsOfProgrammingInterviews 2 | This is a project that helps me and my friends to prepare programming interviews using the book, "Elements of Programming Interviews" 3 | 4 | Update: As I started practising more and more questions, I realized that python is a great language however it is a high-level language. As someone who's usually more on the theoretical side, I decided to switch to Java which requires a bit more low-level thinking. Therefore, much of the code here will be continued in Java. 5 | 6 | ## For Whom 7 | People who have multiple work projects, a hectic scheudle and little time to prepare. 8 | 9 | ## Introduction 10 | Let's try to be really focused and efficient about studying different problems. 11 | 12 | Language: 13 | - Python3 14 | - Java 15 | 16 | Books: 17 | 1. [Elements Of Programming Interviews Python Insiders](https://www.amazon.com/Elements-Programming-Interviews-Python-Insiders/dp/1537713949/ref=pd_lpo_sbs_14_img_1?_encoding=UTF8&psc=1&refRID=VBRYDAK8D3MC47K12V2Z) 18 | 2. [Introduction to Algorithms](https://www.amazon.com/Introduction-Algorithms-3rd-MIT-Press/dp/0262033844) 19 | 3. [Cracking the Coding Interview](https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850/ref=sr_1_1?ie=UTF8&qid=1507572545&sr=8-1&keywords=cracking+the+coding+interviews) 20 | 4. [Introduction to Programming in Java](http://introcs.cs.princeton.edu/java/home/) Note: This book has a lot of materials online, includes chapter and section summaries, and example code, etc. 21 | 22 | Key focus areas: 23 | - Data Structures 24 | - Algorithms 25 | - System Design 26 | 27 | Other Resources: 28 | - [MIT Algorithm class](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/) 29 | - [Cracking the Coding Interview videos](https://www.youtube.com/playlist?list=PLX6IKgS15Ue02WDPRCmYKuZicQHit9kFt) This is speically useful for refreshing your memories on most of the algorithms. 30 | 31 | 32 | ## Chapter 4 Primitive Types 33 | 34 | Chapter 1-3 are about non-technical parts of programming interviews, e.g. resume. We will skip these. 35 | 36 | ### Key Concepts 37 | - Booleans, integers and characters (in Python everything is an object) 38 | - [Build-in types: numerics, sequences, mappings, etc](https://docs.python.org/3/library/stdtypes.html) 39 | - [sys.maxsize](https://docs.python.org/3/library/sys.html#sys.maxsize) 40 | - [sys.float_info](https://docs.python.org/3/library/sys.html#sys.float_info) 41 | - [XOR](https://en.wikipedia.org/wiki/Exclusive_or) 42 | - [Two's complement](https://wiki.python.org/moin/BitwiseOperators) 43 | - [Python: bit-wise operators](https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types) 44 | - [Java: Bitwise and Bit Shift Operators](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html) 45 | 46 | 47 | 48 | ### Problems 49 | Each link takes you directly to the code with comments 50 | - [Count Bits](chapter4/count_bits.py) in Python3 51 | - [Number Complement](chapter4/476NumberComplement.java) from [Leetcode problem number 476](https://leetcode.com/problems/number-complement/description/) 52 | 53 | 54 | *[Typo] At the bottom of page 23, it should be "-16>>2".* 55 | --------------------------------------------------------------------------------