Collection of interesting questions and solutions that involve data structures, algorithms and concepts. Solutions are in Python version 3.4.3
- Data Structures, Algorithms & Concepts
- Brain Teasers (Basic)
- Brain Teasers (Moderate)
- Sort
- Lists & Dictionaries
- Strings
- Permutations and Combinations
- Linked Lists
- Stacks
- Queue & Double-ended queue
- Binary Trees
- Binary Search Tree (BST)
- Heap
- Graph
- Dynamic Programming
- Design & Algorithms
- Bitwise Operations
- Online Resources
- Python Resources
- Interview Resources
- Amazing Technical Discussions
- Data structures, algorithms, time complexity and concepts π πΆ
- Introduction to Concurrency π πΆ
- Introduction to Design Pattern πΆ
- Introduction to Bit Manipulation π₯ πΆ
- Fun with Bits & Bytes π
- Fun with Permuation and Combination π₯ πΆ
- Convert celsius to fahrenheit
- Find sum of all even numbers for a given range
- Find factorial of n
- Find square root of a number
- Find square root without using sqrt function
- Find power of a number
- Fibonacci series
7.1 Find the Fibonacci numbers between the given range
7.2 Find odd numbers in the Fibonacci series for a given range - Write an "echo" program
- Number of perfect squares between two given numbers
- Find all possible numbers which multiply to a give number
- Can you fix an almost sorted list with one swap (such that the result is sorted)? πΆ
- Check if a given number is prime
- How many trailing zeros are in n! (n factorial) π
- Reverse an integer
- Find the Greatest Common Divisior (GCD) of two positive integers
- Validate Sudoku π¨
- Flatten an object representation. Example {a:1, b:2, c:{d:3}} flattens to {a:1,b:2,c.d:3} π₯ π
- Matrix
7.1 Print the matrix from outside to inside (Spiral) π₯
7.2 Given a two dimentional matrix where values are increasing. Search for a target value π πΆ
7.3 Rotate a 2D matrix clockwise 90 degrees
7.4 Rotate a 2D matrix anti-clockwise 90 degrees π - Number of perfect squares between two given numbers
- Find the coordinates of the rectangle in the 2 dimensional list [TODO]
- Check if a number is a happy number
- Given an integer and returns all possible combinations of its factors
- Given a digit string (from phone keypad), return all possible letter combinations that the number could represent
- References
- Compute all permutations of a string
- Find all possible combinations for a given string
- Compute all possible string combinations that can be made my placing spaces (zero or one) between them
- Given a string containing only digits, restore it by returning all possible valid IP address combinations
- Given a phone number provide possible letter mnemonics
- Can you create the given word from the dictionary? π
- Given a set of characters and a positive integer k, print all possible strings of length k that can be formed π
- Given a word and a dictionary. Find all possible words can you make that are found in the dictionary?
- Given a string and pattern with 1's and 0's find the minimum # of turn needed to make sure the pattern does not appear in the string π
- Introduction to bitwise operations
- Bitwise addition
- Bitwise subtraction
- Given a number n, check whether the number is a power of 2
- Given a number n, multiple the number by 2^k
- Compute n^k using bit operations π₯ π
- Swap two variable values without additional space
- Write an efficient program to unset the right most bit and count number of 1s in binary representation of an integer
- Given a list of repeating integers find the lonely integer
- Generate rand7 using rand5 π‘
- Sorting Algorithms & Notes
1.1 Quick Sort π
1.2 Quick Selection Sort π
1.3 Merge Sort
1.4 Heap Sort π π₯
1.5 Insertion Sort
1.6 Bucket Sort
1.7 Radix Sort - Sort lists,lists of lists and list of dictionaries
- Sort a list of ones, twos and threes
- Given two sorted list merge them
- Merge sorted lists
- Sort version numbers π π₯
- Median
7.1 Find median of a sorted list
7.2 Find median of two sorted list π‘ π π
7.3 Find median of unsorted list π‘ πΆ
7.4 Find median in a stream of integers (running median) π πΆ π¨ - Unsorted list of values
8.1 Find the smallest K
8.2 Find the largest K - Merge K sorted list of size N π¨ π‘
- Sort a string
- Find the first and second largest value in an unsorted list
- Given a sequence of words, print all anagrams together π‘
- Sort a string of printable characters π
- Implement skip list
- Implement Trie - insert, search, searchWith, delete (Prefix Tree) πΆ π‘
- Implement Bloom Filter π‘ π₯
- Implement Suffix Array πΆ π‘
- Search using Regular Expression
- KMP (Knuth Morris Pratt) algorithm π₯ π
- Implement Z algorithm
- Find the missing number in an increasing sequence (1 ...N) π‘
- Given a list of integers with duplicates (can be more than one) find any integer than appears more than once
9.1 Can modify the input list
9.2 Cannot modify the input list - Given unsorted values with several duplicates and one value that occurs once find the value TODO
- Find duplicates given 2 sorted lists
11.1 both list of same size
11.2 one list is >> other - Given a two dimentional matrix where values are increasing. Search for a target value π πΆ
- Given a sorted list find if a value exists π₯
- Randomize list elements
- Given two numbers as list add them and return result as list
- Say as you see - given an input string of integers print the output π
- Given a list of numbers, return a list of products of all other numbers without using division in O(n) time π‘ πΆ
- Design a dictionary that performs insert, lookup and delete in constant time O(1)
- Find the majority element π₯
6.1 From unsorted list in linear time and constant storage π
6.2 From sorted list in logrithmic time and constant storage π π‘ - Two lists
7.1 Find the intersection of two sorted lists π
7.2 Given two lists, find a pair of values (one from each array) such that you can swap so that both arrays sum to the same value [TODO]
7.3 Given two sorted list merge them
7.4 Merge sorted lists
7.5 Find min value of two unsorted lists π‘ π - Duplicates
8.1 Given a list of integers return a list of integers that only occurred once π‘ π
8.2 Given a sorted list, remove the duplicates in place, return modified list and #unique values πΆ - Given a list and condition
9.1 Find all possible 2 numbers in the list that add up to the given sum
9.2 Find all possible triplets in the list that add up to the given sum
9.3 Find all possible triplets in the list that satisfies a^2 + b^2 = c^2 πΆ π₯
9.4 There are numbers from 1 to N in an array. One of the number gets duplicated and one is missing. Find out the duplicate number πΆ [TODO]
9.5 Given two arrays of integers, find a pair of values (one from each array) you can swap so that both arrays sum to the same value [TODO]
9.6 Find three numbers when multipled provide max value from the given input
9.7 Find all possible quadruplets in the list that add up to the given sum - Subarray and condition
10.1 Find a continuous subarray of sum zero πΆ π
10.2 Find a continuous subarray of sum target given positive values πΆ
10.3 Find a continuous subarray of sum target given positive and negative values πΆ π
10.4 Print alternate positive and negative values while retaining order π₯
10.5 Find pairs in an integer whose sum is equal to a given value
10.6 Given a list of integers and two target values find the shortest distance between the two target values π₯ πΆ
10.7 Find the pivot value that splits the list into balanced partitions πΆ π‘
10.8 Find the maximum subarray sum - Kadane Algorithm πΆ π‘
10.9 Find #occurrences of the largest sum contiguous subarray of modulo K π¨ π‘
10.10 Given a list and a number K, print the maximum sum subarray of size K - Rotated list
11.1 Rotate a list to the right or left by n places
11.2 Find minimum in a rotated sorted list #RotationPoint π π°
11.3 Search a target number in a rotated sorted list π‘ - Time intervals
12.1 Merge overlapping time intervals πΆ
12.2 Find #conflicting appointments π
12.3 Find conflicting appointments
12.4 Find the next earliest availability given availability and meeting duration π πΆ - Design π‘
13.1 Design a data structure that implements insert, remove, contains and get random in O(1) time π‘ π π
13.2 Design a data structure that implements increment, decrement, max and min in constant time π¨ πΆ π
13.3 Implement a function that inserts, deletes and getrandom in O(1) time πΆ π‘
13.4 Write a function that returns values randomly, according to their weight π‘ πΆ
- Find #words in a sentance
- Find most and least frequently used words in a sentance
- Write a function which finds a closest pair of equal entries π
- Write a function that given an integer returns a formatted number string π π‘ π
- Given a string for a text message and character limit. Break the message without breaking the words and include message count πΆ
- Properties
6.1 Given two strings find if they are Anagrams
An Anagram is a rearrangement of the letters of one word or phrase to form another word or phrase
6.2 Check if two given strings are Isomorphic
Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2. And all occurrences of every character in βstr1β² map to same character in βstr2β²
6.3 Generate all Numeronyms for a given string
A numeronym is a number-based word. Letters between the first and last are replaced with a number representing the number of letters omitted, such as "i18n" for "internationalization" - Reverse
7.1 Reverse an integer π
7.2 Reverse a string recursively
7.3 Reverse all words in a sentance - Palindrome
8.1 Test if a string is a Palindrome. Ignore all non-alphanumeric characters
8.2 Given a number find the next largest Palindrome π‘ πΆ
8.3 Find the longest palindromic substring - Manacher's algorithm π‘ πΆ π - Substring (A substring is a prefix or suffix of any string. There are n^2 substrings.)
9.1 Find the number of distinct substrings of a given string π‘
9.2 Generate all the substrings of a string
9.3 Find first occurance of substring
9.4 Find the longest repeating substring (longest substring of a string that occurs at least twice) π₯ π‘ πΆ
9.5 Find the longest substring with two unique characters πΆ π
9.6 Find the longest substring with k unique characters
9.7 Find the longest substring with non-repeating characters
9.8 Longest Substring with At Most K Distinct Characters π¨ π
9.9 Find the minimum length of the substring that contains all characters in a given input π
10.Given an input string and pattern find the minimum window in the input string that will contain all the characters in the pattern πΆ π - Find the first non repeating character in string
- Linked List Library π π₯
- Linked List Introduction
2.1 Single Linked Lists
2.2 Double Linked Lists - Find the nth node from the end of a linked list πΆ π‘
- Circular Linked List, Cycle & Intersection
4.1 Find the length and start node for the cycle in a linked list π‘ πΆ
4.2 Find the node at which the intersection of two single linked lists begins
4.3 Add a node to a sorted circular linked list π‘ πΆ - Merge
5.1 Merge two sorted linked lists [TODO]
5.2 Merge K sorted linked lists [TODO] π₯ - Given a single linked list with one digit positive integer value
6.1 Add 1 [TODO]
6.2 Add given value [TODO] - Reverse a linked list π π
- Check if a linked list is a Palindrome
- Find the middle element in a linked list π‘
- Delete a node in the linked list πΆ π₯
- Zip a linked list πΆ π
- Split a link list into odd and even values with no additional space π
- Remove duplicate values & retain order of existing values π₯
- Design and implement Least Used Cache (LRU) π‘ πΆ π
- Implement skip list
- Given linked list return max value at any given time in constant time
- Swap adjacent nodes of a linked list [TODO]
- Return a linked list that contains the intersection of two linked lists πΆ
- Implement stack using list
- Implement stack using linked list
- Implement stack using dynamic array
- Implement stack using fixed size array
- Implement stack with getMax() that operates in constant time π
- Check if a string containing parenthesis'()' is balanced π
- Check if a string containing just the characters '(', ')', '{', '}', '[' and ']'is balanced
- Find the length of the longest valid parenthesis sequence in a string, in O(n) time πΆ π
- Given a string where each character can be [0-9] or [+-*] find the result π
- Find top 3 and bottom 2 values from the list in O(n) π
- Implement stack using queue [TODO]
- Compute largest rectangle area under a histogram π πΆ π¨
- Design an algorithm for computing the k-th largest element in a sequence of elements. It should run in O(n) expected time where n is the length of the sequence, which is not known in advnance. The value of K is known in advance. Print the k-th largest element after the sequence has ended. It should use O(k) additional storage [TODO]
- Expression evaluator π
14.1 Single digit
14.2 Multiple digits - Find longest file path π¨
- Implement queue using list
- Implement queue using linked list
- Implement a queue using two stacks
- Queue implementation using dynamic array
- Queue implementation using fixed size array
- [Design an algorithm to sort a stack in descending order] (https://github.com/harishvc/challenges/blob/master/sort-stack-in-descending-order.py)
- Sliding Window Maximum π πΆ π₯
- Implement getMax() that operates in constant time π
8.1 Given a queue return max value at any given time in constant time
8.2 Given linked list return max value at any given time in constant time - Given a screen with all pixels having one of two colors. When a random pixel is clicked, then that pixel & all the adjacent pixels with same color should change the color to the second color [TODO]
- Implement blocking queue [TODO]
- Implement non-blocking queue [TODO]
- Binary Tree Traversal Library π π
1.1 Pre-order
1.2. In-order
1.3. Post-order
1.4 Level-order- 1.4.1 Print tree level by level
- 1.4.2 Print one tree level each line πΆ
- 1.4.3 Add nextRight attribute to each node πΆ π π¨
- 1.4.4 Print nodes in spiral order π‘ TODO
- Essentials
2.0 Binary Tree Essentials Library π π
2.1 Find # of leaves, half nodes and nodes in a binary tree
2.2 Find the size of a binary tree
2.3 Find the height (max depth) of the binary tree πΆ π
2.4 Find the depth (level) of a node and the path from the root
2.5 Find the deepest node in binary tree
2.6 Find diameter (width) of a binary tree π πΆ π‘
2.8 Find all edge nodes (boundary/perimeter) in the binary tree π - Path Sum
3.1 Find the max value of the binary tree
3.2 Find level than has maximum sum π
3.3 Given path sum check if the path exists π
3.4 Root to leaf path (Iterative)
3.5 Root to leaf path (Recursive) π¨ π‘
3.6 Find the sum of all root to leaf paths where each path represents a binary number π π π‘
3.7 Find sum of all leaf nodes
3.8 Find the sum of all left leaves - Moderate Difficulty
4.1 Flip/Invert a binary tree π
4.2 Clone a binary tree π
4.3 Check if a binary tree is symmetric (mirror)
4.4 Check if two binary trees are structurally identical? π
4.5 Complete Binary Tree
Β Β Β Β Β 4.5.1 Find # nodes in a Complete Binary Tree π‘ π
Β Β Β Β Β 4.5.3 Check if a Binary Tree is Complete Binary tree?
4.6 Balanced Binary Tree
Β Β Β Β Β 4.6.1 Check if a binary tree is fully balanced π π‘
Β Β Β Β Β 4.6.2 Add a node to a balanced binary tree
Β Β Β Β Β 4.6.3 Given a full binary tree, add a pointer to the next sibling
4.7 Given two binary trees T1 and T2, check if T2 is a subset of T1 π‘ πΆ π
4.8 Find the ancestors of a node in a binary tree π πΆ π
4.9 Find the Lowest (nearest/first) Common Ancestor (LCA) of two nodes in a binary tree
Β Β Β Β Β 4.9.1 Traverse down - parent node to child node π πΆ π
Β Β Β Β Β 4.9.2 Traverse up - child node to parent node
4.10 Find the shortest path between two nodes in a binary tree π πΆ π
Β Β Β Β Β 4.10.1 solution 1: Modify LCA
Β Β Β Β Β 4.10.2 solution 2: Using root to node path
4.11 Given a binary tree where path are from parent node to child node, root and leaf can be excluded in the path
Β Β Β Β Β 4.11.1 Count # path that add up to a given value π‘ π
Β Β Β Β Β 4.11.2 List all the path that add up to a given value π
4.12 Serialize and Deserialize a Binary tree π₯ π π
Β Β Β Β Β 4.12.1 From pre-order with leaves and half-nodes marked π‘
Β Β Β Β Β 4.12.2 From pre-order & in-order
Β Β Β Β Β 4.12.3 From post-order & in-order
4.13 Given preorder and inorder traversal construct postorder traversal π₯ π
4.14 Construct a binary tree from per-order traversal where leaf nodes are marked π‘ πΆ
- BST Library (add node,delete node, isBST? max, min)
- Create BST
1.1 Convert a unsorted list to BST
1.2 Convert a sorted list to BST πΆ - Delete node from BST π
- Find max value of BST
- Find min value of BST
- Find if an element exists in BST
- Check if valid BST π
- Find inorder successor of node N π π¨ π πΆ
- In a BST given a target find a value close to the target
- Find smallest K in a BST π π‘
- Find largest K in a BST π π‘ π
- Given a BST find # nodes that lie in the given range
- Search in sorted list X for index i such that X[i] = i π‘ π
- Given a sorted list create a BST with minimal height π π‘
- Given ordered nodes construct a fully balanced BST π
- Find all possible combinations that can generate identical Binary Search Tree (BST) π‘ π π π¨
- Given a sorted list and a value, find the first and last occurance of the value π‘ πΆ
- Find the square root of an integer without using square root function π‘
- Find mean of a BST
- Find the Lowest (nearest/first) Common Ancestor (LCA) of a BST π‘ πΆ
- Find depth of a binary search tree without using recursion
- Implement BST iterator π π‘ πΆ
- Find size of BST tree in a Binary Tree πΆ π
- Delete nodes outside the given range in BST π‘ πΆ
- Fundamentals
1.1 Convert unsorted list to max heap in linear time π π
1.2 Insert value into a heap π
1.3 Check if a Binary tree is a Complete Binary Tree [TODO]
1.4 Heap Sort - Moderate
2.1. Find Kth maximum in an unsorted list
2.2. Find the Kth most popular value in an unsorted list
2.3. Find K popular values in an unsorted list - Advanced
3.1 Merge K sorted list of size N
3.2 Maintain a Max Heap of size K
- Fundamentals
1.1 Directed Acyclic Graph (DAG)
1.2 Depth First Traversal
1.3 Breadth First Traversal π π₯
1.4 In a directed graph given two nodes find out whether if a path exists
1.5 Topological Sort (given edges)
1.6 Topological Sort using Kahn's algorithm (given adjacency list) πΆ π - Moderate
A cycle is a closed path - visit a node for the second time before all its decendents have been visited
2.1 Detect cycle using Depth First Traversal π πΆ
2.2 Detect cycle using Topological Sort
2.3 Given a sorted dictionary (array of words) of an alien language, find order of characters in the language
2.4 Given a trip start and destination print the itenary
2.5 Find longest path in a Directed Acyclic Graph from a source vertex π₯ - Advanced
3.1 Dijkstra shortest path algorithm [TODO]
3.2 Given a source word, target word and dictionary, transform the source word to target by changing/adding/removing 1 character at a time, while all intermediate words being valid words in the dictionary. Return the transformation chain which has the smallest number of intermediate words #WordLadder π π
3.3 Given a boolean 2D matrix, find the number of islands πΆ π
3.4 Given a graph find the Strongly Connected Components (SSC) πΆ π
- Multiply two numbers without using operators *, / and with minimal operations π
- Find the power set πΆ π‘
Power Set is a set that includes all the subsets including an empty set and the set itself.
2^N subsets for a set of size N - Generate all possible N pairs of balanced parentheses π π‘
- Find string combinations of length K
- Find all permutations of a string in sorted (lexicographic) order - should handle duplicate values πΆ π π‘
- Given stock prices during a time period find maximum gain
6.1 singe purchase and sale π
6.2 Multiple single purchases and sales without overlaps π¨ π - Partition
7.1 Can the given list be partitioned into two sub-lists with equal sum (balanced partition)?πΆ
7.2 Given a list, identify two sub-lists with equal sum (balanced partition, using DP) π π‘
7.3 Given a list, identify all sub-lists with equal sum (balanced partition, using back tracking) πΆ - Longest Increasing Subsequence (LIS)
8.1 Given a list of random numbers. Find length of Longest Increasing Subsequence (LIS) and the sequence πΆ
8.2 Given a list of random numbers. Find all the increasing subsequences - Given n stairs to reach the top and you can take 1 or 2 steps at each stair
9.1 Find #ways a person can reach the top of the stairs πΆ
9.2 Find all possible combinations π‘ - Given target and possible values
10.1 Find #combinations to achieve the target πΆ π
10.2 Find all unique combinations to achieve the target π¨ - Given denominations and a total
11.1 Minimum # coins needs to reach the total and what are the coins? π πΆ
11.2 Find all possible combinations to reach a total π‘ π₯
11.3 Find all possible combinations to reach a total using lookup π‘ π₯ - Determine the maximum possible value from the coin play game π πΆ π‘
- What is the minimum attempts to find out from which floor egg will break?
13.1 2 Eggs π¨ π π‘
13.2 N eggs πΆ π - How many different 10-digit numbers can be formed starting from 1? movement from 1 digit to the next is similar to the movement of the Knight in a chess game π‘ π
- Find the nth Fibonacci number
15.1 Iterative, Recursive, Bottom-up & Top-down
15.2 Recursive with lookup - Longest Common Subsequence (LCS) π₯ π
subsequence is a generalization of substring. For example, "Itwastimes" is a subsequence of "It was the best of times", but not a substring
16.1 Length of the LCS
16.2 Find the LCS
16.3 Find all the sequences π
16.4 Implement Unix diff command - Longest Common Substring
17.1 Length of the Longest Common Substring
17.2 Find the Longest Common Substring
17.3 Longest common substring of more than two strings - Find #steps to convert string1 to string 2 using operations insert,remove,replace π π
- Input string and dictionary of words
19.1 Can the input word be split using space-separated sequence of dictionary words? πΆ π¨
19.2 Construct all possible sentences where each word is a valid dictionary word π‘ π - Given two sequences find the longest palindrome
- Text justification
21.1 Given a string and limit provide line breaks based on even distribution of empty spaces π‘ πΆ
21.2 Pack your words in a greedy approach, evenly distribute space TODO - Binary matrix
22.1 Find #path from top left to bottom right π‘
22.2 Find out the maximum square size sub-matrix π πΆ
22.3 Find area of the largest rectangle π π‘ πΆ
22.4 Find #rectangles - Matrix multiplication
23.1 Find the most efficient way to multiply these matrices πΆ π‘
23.2 Find the order in which the matrices need to be multiplied - Given the weight and a value of cakes and a duffel bag with max capacity, find the max value that can be filled in the duffel bag π‘ π¨
- Given a million points (x, y), give an O(n) solution to find the n points closest to (0, 0)
- Implement T9
- How to find list of possible words from a letter matrix (Boggle)
- Given a family tree, find oldest sisters of the given person, oldest sister in the family tree and the oldest ancestor
- Design a command line alarm clock
- Design a rate limiting web service π₯ π‘ πΆ
- Using OOP design a elevator πΆ
- Design a data structure that implements insert, remove, contains and get random in O(1) time π‘ π π
- Design a data structure that implements increment, decrement, max and min in constant time π¨ πΆ π
- Implement a function that inserts, deletes and getrandom in O(1) time πΆ π‘
- Write a function that returns values randomly, according to their weight π‘ πΆ
- Top 10 Algorithms for Coding Interview π₯ π
- Problem Solving with Algorithms and Data Structures
- Data Structure and Algorithmic Thinking with Python π₯ π
a. Book@Amazon
b. GitHub Repository - Cracking the Coding Interview (6th Edition) π₯ π
a. Book@Amazon
b. GitHub Repository
c. Resources - Tushar Roy π₯ π
a. Interview Questions Wiki
b. YouTube Playlist - Dynamic Programming Introduction π
- Popular Dynamic Programming Interview Questions π
- The Hitchhikerβs Guide to the Programming Contests (PDF)
- Two-phase commit protocol
- Juan Elices Leetcode blog
- Magic of XOR
- The idea behind big O notation
- A beginner's guide to Big O notation πΆ
- Know Thy Complexities!
- Bucket Sort Visualization
- Properties of Pascalβs Triangle
- Python Module of the Week
a. Python 3 π
b. Python 2 - Python Interview Questions @ Interview Cake
- Python Interview Questions @ Intellipaat πΆ
- Python List Comprehension With Examples
- dis β Python Bytecode Disassembler
- Python debugger cheat sheat
- Python exception handling - try/except/else/finally
- Real-World Regular Expressions for Python
- The Python Tutorial (version 3.4)
- Python Programming.Net
- Popular Python recipes @ ActiveState
- Object-oriented concepts in Python
- Porting Code to from Python2 to Python3 πΆ
- Hacker Rank Warmup! π
- I DESERVE TO LEARN π π
- Google interview questions - Product & Software Engineer
- How to avoid and outlive layoffs as a programmer?
- How do I prepare for a software engineering job interview? - Discussion on Quora
- Data Structure tutorials from Eternally Confuzzled
- Andrei Simionescu GitHub Respository with code and numerous online resources
- Recent interview questions@Career Cup
- Interview questions on reddit
- JavaScript interview questions
- Building Systems and Apps @Scale - archived videos on YouTube π‘