Playground for popular algorithms and data-structures problems.
-
Snake and Ladder Problem: Given a snake and ladder game, find the minimum number of dice throws required to reach the destination from source. (Solution)
-
Course Schedule There are a total of
numCourses
courses you have to take, labeled from0
tonumCourses-1
. There are course prerequisites like [0,1], meaning to take0
you have to1
first. Find out if it is possible for you to finish all courses? Ref. (Solutions: ruby, java) -
Reorder Routes to Make All Paths Lead to the City Zero, ref. (Solution)
-
Surrounded Regions Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region, ref. (Solution)
-
Find shortest distances between every pair of vertices of weighted directed Graph - Floyd–Warshall's Algorithm, ref. (solution)
-
Binary search (Solution)
-
Ternary Search (Solution)
-
Subarray with given sum, non-negative numbers. (Solution)
-
Rearrange an array in maximum minimum form, O(1) extra space. (Solution)
-
Maximum Subarray: given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. (Solution)
-
Move all zeroes to end of array with minimum operations and in-place (Solution)
-
Sort an array of 0s, 1s and 2s (Solution)
-
Equilibrium point/index of an array (Solution)
-
Reverse an array in groups of given size (details). solution
-
Counting Elements - Given an integer array, count element
x
such thatx + 1
is also in array. If there're duplicates in array, count them seperately. (Solution) -
Last Stone Weight - Given an integer array as collection of stones, Each turn, we choose the two heaviest stones and smash them together. The result of this smash is: If
x == y
, both stones are totally destroyed otherwise weight ofx
is destroyed, and the stone of weighty
has new weight y-x (Solution) (Solution in java) -
Contiguous Array Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. (Solution)
-
Product of Array Except Self Given an array of integers, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Without using division. (Solution)
-
Find the point where maximum intervals overlap (Solution)
-
Maximum Sum Circular Subarray (Solution)
-
Online Stock Span : collect daily price quotes of a stock and return the
span
of the stock's price for the current day. Span of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backwards) for which the price of the stock was less than or equal to today's price. For example, if the price of a stock over the next 7 days were[100, 80, 60, 70, 60, 75, 85]
, then the stock spans would be[1, 1, 1, 2, 1, 4, 6]
. (Solution) -
Find leaders : An element is leader if it is greater than all the elements to its right side, rightmost element is always a leader. (Solution)
-
Interval List Intersections : Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order. Return the intersection of these two interval lists. Ref. (Solution in ruby), (Solution in java)
-
Search Insert Position Given a sorted array and a target value, return the index if the target is found otherwise return the index where it would be if it were inserted in order ref. Solution
-
H-Index II Given an array of citations sorted in ascending order of a researcher, write a function to compute the researcher's h-index, ref. (solution)
-
Avoid Flood in The City full details
-
Given a sorted and rotated array, find if there is a pair with a given sum (ref)
-
Duplicates in an array : Given an array containing elements from
0
ton-1
, with any of these numbers appearing any number of times, find these repeating numbers in O(n) and using only constant memory space. (ref). solution -
Relative Sorting : Sort A1 in such a way that the relative order among the elements will be same as those in A2. For the elements not present in A2, append them at last in sorted order (ref). solution
-
Trapping Rain Water (ref):
-
Find the minimum element in a sorted and rotated array (ref).
-
Reverse a linked list
-
Merge two sorted linked lists such that merged list is in reverse order. (Solution)
-
Merge two sorted lists (in-place).
-
Merge k sorted lists or Flattening a Linked List, ref
-
Sort a linked list of 0s, 1s and 2s by changing links (Solution)
-
Add two numbers represented by linked lists, digits are stored in reverse order and each node contain a single digit. (Solution)
-
Add two numbers represented by linked lists. Lists are non-empty. Reversing the lists is not allowed (details). solution
-
Rotate a Linked List counter-clockwise by k nodes, where
0 < k <= len(list)
(Solution) -
Remove loop in Linked List (Solution)
-
Intersection of two Sorted Linked Lists (ref)
-
Reverse a Linked List in groups of given size.
-
Flatten a multilevel linked list in way that all nodes at first level should come first, then nodes of second level, and so on. (ref). solution
valid_path.rb
-
Maximum width of a binary tree. (Solution)
-
A program to check if a binary tree is BST or not. (Solution)
-
Height of Binary Tree. (Solution)
-
Binary Search Tree - Search and Insertion (Solution)
-
Print left view of Binary tree (Solution)
-
Construct bst from preorder traversal (Solution)
-
Diameter of Binary Tree : Diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. (Solution)
-
Convert a Binary Tree into its Mirror Tree. Also known as Invert Binary Tree (Solution)
-
Root to leaf path sum equal to a given number (Solution)
-
Check if tree is Symmetric i.e. mirror image of itself (Solution)
-
Double Tree (Solution)
-
Maximum Path Sum from one leaf node to another of a binary tree. (ref).
-
Convert a given Binary Tree to Doubly Linked List in-place, ref
-
Given a complete binary tree, count the number of nodes, ref. (solution)
-
Given a binary tree containing digits from
0-9
only, each root-to-leaf path could represent a number, ex: path1->2->3
represents the number 123. Find the total sum of all root-to-leaf numbers ref. (solution) -
Maximum difference between node and its ancestor in Binary Tree, ref. (solution)
-
Lowest Common Ancestor in a BST, assuming both the values exist in the tree. solution
-
Vertical Order Traversal of a Binary Tree, (ref).
-
Path Sum III Each node of the tree contains an integer value, find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards, (ref). solution
-
Check if a binary tree is subtree of another binary tree (ref). solution
-
Preorder to Postorder : Given an array of N nodes representing preorder traversal of BST, print its postorder traversal in O(N) time (ref). solution
-
Find k-th smallest element in BST (Order Statistics in BST) (ref). solution
-
Check if given Binary Tree is Height Balanced or Not (details). solution
-
Backspace String Compare: Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. (Solution)
-
Perform String shifts: given list of pairs
[direction, amount]
to perform shift on a given string.direction
0 means left shift and1
means right shift. (Solution) -
Group Anagrams: given an array of strings, group anagrams together. (Solution)
-
Valid Parenthesis String string has 3 types of characters:
(
,)
and*
.*
can be treated as(
or)
or empty string. (Solution) -
Balanced parenthesis : determine if are the parenthesis balanced in a given string
-
Making File Names Unique Given a list of names, create
n
folders in your file system such that, create a folder for every name. Since two files cannot have the same name, if you enter a folder name which is previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique, ref. (solution) -
Reverse words in a string OR reverse string word by word
- manage extra spaces : solution
- in place : solution
-
Partition Labels : partition the given string into as many parts(groups) as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts. For example: for string
"ababcbacadefegdehijhklij"
result would be[9,7,8]
(ref). solution -
Roman Number to Integer. solution
-
Longest Palindrome in a String (ref).
-
Length of the longest substring without repeating characters (ref). solution
-
QuickSort for array (Solution)
-
3-Way QuickSort (Dutch National Flag)
-
Min Stack : Design a stack that supports push, pop, top, and retrieving the minimum element in constant time (details). (Solution)
-
Evaluation of Postfix Expression ex:
'1 2 3 + * 8 -'
=>-3
, ref. (solution)
-
Flood fill Algorithm (Solution)
-
Count square submatrices with all ones (Solution)
-
Set every cell in matrix to 0 if that row or column contains a 0 (details, details). solution
-
Trie operations with prefix search i.e.
insert
,search
,starts_with
, ref. (Solution) -
Add and Search Word - Data structure design, (ref). solutuon
-
Auto-complete feature using Trie. solution
-
Making Change Given an amount and coins, write a function to compute the minimum number of coins required to make that amount of change.
-
0-1 Knapsack You have a knapsack which can carry a certain maximum amount of weight and you have a set of items with their own weight and a monetary value. You can only carry what fits in the knapsack. Find the maximize amount of money that you can earn.
-
Paint House III Given an array
houses
, anm * n
matrix cost and an integertarget
, return minimum cost of painting all the remaining houses in such a way that there are exactlytarget
neighborhoods, if not possible return-1
(ref)- recursive solution brute force
- top-down solution
-
Target Sum Given a list of non-negative numbers and a target, S. Find the number of ways that we can
add
andsubtract
the values innums
to add up to T (ref). -
Coin Change 2 Find number of combinations that make up that amount, assume that you have infinite coins (ref).
-
Find maximum possible stolen value from houses (ref). solution
-
Word Break II Given a non-empty string
s
and a dictionary wordDict, add spaces ins
to construct a sentence where each word is a valid dictionary word. Return all such possible sentences, ref. solution -
Longest Common Substring ref.
-
The Hamming distance between two integers is the number of positions at which the corresponding bits are different, ref. (solution)
-
Position of first set bit found from right side in the binary representation of given the number. (solution)
-
Find most significant set bit of a number. (solution)
-
Print all distinct permutations of a given string. (solution)
-
Insert Delete GetRandom O(1) or Randomized Set Design a data structure that supports all the operations in constant time O(1) ref. Solution
-
Given a list of
coordinates
, find if all of them are part of a same straign line. solution -
Ugly Number II Program to find
nth
ugly number i.e. a positive number whose prime factors only include2, 3, 5
, ref. -
Subsets or Powerset for given set of distinct integers, ref
-
Find all prime factors of a given number in increasing order. solution
-
Given a non-negative index k where 0 ≤ k ≤ 33, return the kth index row of the Pascal's triangle (ref). solution
-
Iterator for Combination, problem details. solution
-
Find Right Interval (problem details). solution
-
Word Ladder (details). solution, optimized solution
-
Minimum Number of Arrows to Burst Balloons (details). solution
-
Number of Longest Increasing Subsequence (details). solution
-
Convert Binary Number in a Linked List to Integer (details). solution
-
Minimum Cost to Move Chips to The Same Position (details). solution
-
Find the Smallest Divisor Given a Threshold (details). solution
-
Maximum Difference Between Node and Ancestor (details). solution
-
Populating Next Right Pointers in Each Node (details). solution
-
Minimum Deletions to Make String Balanced (details). solution
-
Longest Substring with At Least K Repeating Characters (details). solution
-
Populating Next Right Pointers in Each Node II (details). solution
-
Pairs of Songs With Total Durations Divisible by 60 (details). solution
-
Smallest Subtree with all the Deepest Nodes (details). solution
-
Pseudo-Palindromic Paths in a Binary Tree (details). solution
-
Check Array Formation Through Concatenation (details). solution
-
Find a Corresponding Node of a Binary Tree in a Clone of That Tree (details). solution
-
Check If All 1's Are at Least Length K Places Away (details). solution
-
Concatenation of Consecutive Binary Numbers (details). solution
-
Smallest String With A Given Numeric Value (details). solution
-
Minimum Remove to Make Valid Parentheses (details). solution
-
Longest Word in Dictionary through Deleting (details). solution
-
Divide Two Integers (details). solution , solution in java
-
Integer to Roman (details).
-
Check If a String Contains All Binary Codes of Size K (details). solution
-
Flip Binary Tree To Match Preorder Traversal (ref). solution
-
Find First and Last Position of Element in Sorted Array (details). solution
-
Convert Sorted List to height balanced Binary Search Tree (details). solution
-
Maximum Points You Can Obtain from Cards (details). solution
-
Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts (details). solution
-
Construct Binary Tree from Preorder and Inorder Traversal (details). solution
-
Remove All Adjacent Duplicates In String (details). solution
-
Make Two Arrays Equal by Reversing Sub-arrays (details). solution
-
Lowest Common Ancestor of a Binary Search Tree (details). solution
-
Convert Sorted Array to Binary Search Tree (details). solution
-
Sentence Screen Fitting (details) or for free users(details). solution
-
Replace Words (details). solution, trie based solution
-
Verify Preorder Serialization of a Binary Tree (details). solution
-
Maximum Length of a Concatenated String with Unique Characters (details). solution
-
Shortest Path in a Grid with Obstacles Elimination (details). solution
-
Construct Binary Search Tree from Preorder Traversal (details). solution
-
Minimum Value to Get Positive Step by Step Sum (details). solution
-
Find All Numbers Disappeared in an Array (details). solution
-
Remove All Adjacent Duplicates in String II (details). solution
-
Minimum Deletions to Make Character Frequencies Unique (details). solution
-
Count Unreachable Pairs of Nodes in an Undirected Graph (details). solution
-
Maximum Number of Vowels in a Substring of Given Length (details). solution
-
Count Negative Numbers in a Sorted Matrix (details). solution
-
Longest Subarray of 1's After Deleting One Element (details). solution
-
Longest Arithmetic Subsequence of Given Difference (details). solution
-
Minimize the Maximum Difference of Pairs (details). solution
-
Remove Colored Pieces if Both Neighbors are the Same Color (details). solution