Need help with algorithms_and_data_structures?

Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

4.3K Stars 1.0K Forks GNU General Public License v2.0 369 Commits 156 Opened issues

180+ Algorithm & Data Structure Problems using C++

Readme

| Current Status| Stats | | :------------: | :----------: | | Total C++ Problems | 188 | | Total Python Problems | 15 | | Current Daily Streak| 11 | | Last Streak | 06/20/2019 - 06/21/2019| | Current Streak | 06/23/2019 - 07/03/2019|

**Note: Some of the code here is old and was written when I was learning C++. It might be possible that code is not safe or making wrong assumptions. Please use with caution. Pull requests are always welcome.**

| Problem | Solution |
| :------------ | :----------: |
| Find the nth node of linked list from last. |nthToLastNode.cpp, nth*to*last_node.py |
| Add numbers where each digit of the number is represented by node of a linkedlist. Give output as a linked list. | add*two*numbers_lists.cpp, add*two*numbers_list.py|
| Swap nodes of a linkedlist without swapping data. |swapNodesWithoutSwappingData.cpp, swap*nodes*without*swapping*data.py|
| Reverse a linked list, iteratively and recursively | reverseLinkedListIterAndRecurse.cpp, reverse_linkedlist.py|
| Given a linked list, reverse alternate nodes and append at the end. | reverseAlternateNodes.cpp |
| Only given a node pointer, delete the node from the linked list. | deleteNode.cpp|
| Delete the entire linkedlist. | deleteLinkedlist.cpp|
| Print middle node of linkedlist without iterating twice. | printMiddleNode.cpp | | Detecting and removing a cycle in linkedlist.| floyedCycleDetection.cpp|
| Determine if a linked list is a pallindrome. | listPallindrome.cpp |
| Insert data in a sorted linked list.|insertInASortedLinkedList.cpp |
| Determine the intersection(merging) point of two given linked list.| findIntersectionPointOfLists.cpp, intersection*of*lists.py|
| Clone a linkedlist which has next and an random pointer, Space Complexity - O(1). | cloneListWithRandomPtr.cpp, clone*list*with*random*ptr.py|
| Given a sorted linked list with duplicates, remove duplicates in one iteration. | removeDuplicatesFromSortedList.cpp|
| Using Floyd's cycle finding algorithm, detect if a linkedlist contain cycle, if it does contain cycle, remove the loop | floyedCycleDetection.cpp |
| Sort a linked list using merge sort | merge_sort.cpp |
| Given a singly linked list L_{0} -> L_{1} -> … -> L_{n-1} -> L_{n}. Rearrange the nodes in the list (in place) so that the new formed list is : L_{0} -> L_{n} -> L_{1} -> L_{n-1} -> L_{2} -> L_{n-2 .... |rearrange_list.cpp | }

Include contains single header implementation of data structures and some algorithms.

| Data Structure/Algorithm | Implementation |
| :------------: | :----------: |
| Generic Macros and Algorithms like swap, random number generation | generic.h |
| Generic Stack Implementation | stack.h |
| Generic Queue Implementation | queue.h |
| Generic List Implementation | list.h |
| Binary Search Tree Implementation | binarySearchTree.h |
| Quick Sort Implementation | quickSort.h |
| Merge Sort Implementation | mergeSort.h|
| Selection Sort Implementation | selectionSort.h |
| Bubble Sort Implementation | bubbleSort.h |
| Linux Kernel Double LinkedList Implementation | double*linked*list.h |
| Generic Graph Implementation (Adjacency List) | graph.h |
| Heap Sort Implementation | heap_sort.h|
| My own string library implementation | pstring.h pstring.cpp|

| Problem | Solution |
| :------------ | :----------: |
| Determine if a number is a power of 2. | power*of*2.cpp |
| Add two binary number represented as string. | addBin.cpp |
| Determine the next power of 2 for a given number. | next*power*of_2.cpp |
| Using bit manipulation determine if a number is multiple of 3. | multiple*of*3.cpp |
| Determine endianess of the machine, print a number in reverse Endianess. | reverseEndianness.cpp |
| Find the parity of given number. | find_parity.cpp |
| Implement fast multiplication of a number to 7 using bit manipulation. | multiply*by*7.cpp |
| Reverse bits of unsigned integer (two methods - Reversing bit by bit & divide and conquer). | reverseBitsOfAnInteger.cpp |
| Small function to determine position of right most set bit in a given integer.| right*most*set_bit.cpp|
|Given a vector of numbers, only one number occurs odd number of times, find the number.| find*odd*one_out.cpp|
| Given two integers, determine if their sum would be interger overflow.| integerOverflow.cpp|
| How many bit flip operation would require to convert number A to B. | countNumberOfBitFlips.cpp|
| Given a number x and two positions (from right side) in binary representation of x, write a function that swaps n right bits at given two positions and returns the result. It is also given that the two sets of bits do not overlap.|swapSetOfBits.cpp|
| Add two numbers without using any arithmetic operators | addition*without*operators.cpp|
|Louise and Richard play a game. They have a counter set to N. Louise gets the first turn and the turns alternate thereafter. In the game, they perform the following operations:

- If N is not a power of 2, reduce the counter by the largest power of 2 less than N.

- If N is a power of 2, reduce the counter by half of N.

- Given N, your task is to find the winner of the game. If they set counter to 1, Richard wins, because its Louise' turn and she cannot make a move.

- Input Format : -The first line contains an integer T, the number of testcases. T lines follow. Each line contains N, the initial number set in the counter.

| Problem | Solution |
| :------------ | :----------: |
| Problem 1-1 : Edition 6: Write an algorithm to determine whether a string has unique characters or not. Can we do it without using additional data structures? | 1-1-hasUniqueChars.cpp, 1-1-hasUniqueChars.py|
| Problem 1-2 : Edition 5: Reverse a string when you are a pass a null terminated C string.|1-2-edi5-reverseString.cpp |
| Problem 1-2 : Edition 6: Given two strings, determine if one is permutation of other.|1-2-perm-strings.cpp, 1-2-perm-strings.py|
| Problem 1-3 : Edition 5: Write an algorithm to remove duplicate chars from a string.|1-3-edi5-removeDuplicates.cpp|
| Problem 1-3 : Edition 6: URLify: Replace all the spaces in a string with '%20'. Preferebly Inplace |1-3-URLify.cpp|
| Problem 1-4 : Edition 6: Given a string, write a function to check if it is a permutation of a pallindrome.|1-4-pallindrome-permutations.cpp |
| Problem 1-5 : Edition 6: There are three possible edits that can be performed on a string - Insert a char, Delete a char, Replace a char. Given two strings, determine if they are one or 0 edit away.|1-5-one-edit-away.cpp |
| Problem 1-6: Implement a method to perform basic string compression. Example string **aabcccccaaa** should be compressed to **a2b1c5a3**, however if compressed string is bigger than original string, return original string| 1-6-string-compression.cpp|
| Problem 1-7: Rotate the matrix clockwise( & anticlockwise) by 90 degrees| 1-7-matrix-rotation.cpp|
| Problem 1-8: Write an algorithm such that if an element of MxN matrix is 0, its entire row and column is set to 0. | 1-8-zero-matrix.cpp|
| Problem 1-9: Given two strings s1 and s2, determine s2 is rotation of s1 using only one call to a function which checks whether one string is rotation of another.|1-9-string-rotation.cpp|
| Problem 2-1: Remove duplicates from an *unsorted* linked list. What if no temporary buffer is allowed.|2-1-remove-dups.cpp|
| Problem 2-2: Determine k^{th} node from the last of a singly linked list. (Iterative and Recursive Approaches) | 2-2-kthToLast.cpp|
| Problem 2-3: Implement an algorithm to delete a node in the middle of a singly linked list | 2-3-delete-middle-node.cpp|
| Problem 2-4: Partition a linked list around a value x, all the nodes smaller than x come before all the nodes greater than equal to x | 2-4-partition.cpp|
| Problem 2-5: You have two numberse represented by a linked list where each node contains a single digit. The digits are stored in reversed order, such that 1's digits are at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.Example:

- Input: ( 7 --> 1 --> 6 ) + ( 5 --> 9 --> 2 ) that is 617 + 295

- Output: ( 2 --> 1 --> 9 ) i.e. 912.

- FOLLOW UP : Suppose the lists are stored in forward order, Repeat the above problem.

- Input: ( 6 --> 1 --> 7 ) + ( 2 --> 9 --> 5 ) i.e. 617 + 295

- Output: ( 9 --> 1 --> 2 ) i.e. 912.

- Implement it recursively and iteratively.

| Problem | Solution |
| :------------ | :----------: |
| N^{th} Fibonacci term using different memoization techniques | fibonacci.cpp|
| Longest Common Subsequence Problem | lcs.cpp, longest*common*subsequence.py |
| Maximum Value Contigous Subsequence Problem wiki| max_subsequence.cpp|
| Catalan number - Count the number of possible Binary Search Trees with n keys | catalan_number.cpp|
| Calculate the number of unique paths from source origin (0, 0) to destination (m-1, n-1) in a m x n grid. You can only move either in down or right direction.|unique_paths.cpp|
| 0-1 Knapsack Problem: Imagine you are a thief and you want to steal things with room full of things. You have a knapsack which can handle maximum capacity of weight W, and you want to fill it up such that it's worth is maximum. Being an intelligent thief, you know weights and values of each item in room. How would you fill your knapsack, such that you get the maximum possible value, such that you can only fill upto capacity W.|0*1*knapsack_problem.cpp|

| Problem | Solution |
| :------------ | :----------: |
|Iterative Level order traversal of Tree using queue |levelOrderTraversalIterative.cpp, level*order*tree*traversal*iterative.py|
|Recursive Level order traveral of Tree | levelOrderTraversalRecursive.cpp, level*order*tree*traversal*recursive.py|
|ZigZag Traversal of Tree | zigZagTraversal.cpp, zig*zag*traversal.py|
|Predecessor and Successor of a given node in Binary Search Tree | predecessorSuccessor.cpp|
|Given values of two nodes in a Binary Search Tree, find the Lowest Common Ancestor (LCA). Assume that both the values exist in the tree.| lowest-common-ancestor.cpp, lowest*common*ancestor.py|
|Given a binary tree (unlike binary search tree), find the Lowest Common Ancestor (LCA).|lowest-common-ancestor-binary-tree.cpp|
|Given a binary tree, print out all of its root-to-leaf paths one per line.| printAllRootToLeafPath.cpp
|Determine if a tree is sum tree. A SumTree is a Binary Tree where the value of a node is equal to sum of the nodes present in its left subtree and right subtree. An empty tree is SumTree and sum of an empty tree can be considered as 0. A leaf node is also considered as SumTree.| sumTree.cpp|
|Convert a tree to sumTree, such that each node is sum of left and right subtree of the original tree.| convert*to*sum_tree.cpp, convert*to*sum_tree.py|
| Convert a sorted array to balanced binary search tree.| sortedArrayToBST.cpp|
| Given a binary tree, generate sum of each vertical column.|verticalSum.cpp|
| Given a binary tree and key, node with key exists in tree. Find all the ancestors of the node with key, ancestor here are the nodes which are in straight path from node to root.| node*ancestors*in*root*path.cpp|
| Given a binary tree and key, return the level of the node with key. Root is at level 1, and if node with key does not exists in tree, return 0| level*of*node.cpp|
| Given a binary tree, find all the paths from root to nodes, whose sum is k. | k*sum*paths.cpp|
| Given a binary tree, print its nodes level by level in reverse order. i.e. all nodes present at last level should be printed first followed by nodes of second-last level and so on.. All nodes for any level should be printed from left to right. | reverseLevelOrderTraversal.cpp |
| Invert a binary tree, recursively and iteratively.| invert*a*tree.cpp |
| Given a Binary Search Tree, find ceil and floor of a given key in it. If the given key lie in the BST, then both floor and ceil is equal to that key, else ceil is equal to next greater key (if any) in the BST and floor is equal to previous greater key (if any) in the BST | floor*ceil*bst.cpp |
| Find kth smallest element in a binary search tree | kth_smallest.cpp|
| Validate if a given binary tree is a binary search tree. | validate_bst.cpp |
| Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.| find*target*k.cpp |
| Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. Also, to note that the target value is a floating point. There will be only one unique value which is closest to the target. |closest*bst*value.cpp, closest*bst*value.py |
| Given a binary tree, traversing preorder, construct a string output containing node values and parenthesis. The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree. Examples in code file| string*from*tree.cpp|

| Problem | Solution |
| :------------ | :----------: |
| Implementation of Robin-Karp algorithm for string search | robinKarpStringMatching.cpp |
| Find next permutation of a given string, ie. rearrange the given string sucht a way that is next lexicographically greater string than given string | next_permutation.cpp|
| Implementation of Z algorithm for pattern matching | z.cpp|
| Test cases for self created string library | pstring_test.cpp|
| Get the length of the last word in a string. | length*of*last_word.cpp|
| Find the difference between two string. String t is generated by random shuffling string s and then add one more letter at a random position. Determine the character which is different in t| find_difference.cpp|

| Problem | Solution |
| :------------ | :----------: |
| Print the contents of matrix in a spiral order | matrix*spiral*print.cpp
| Given a M x N matrix, rotate it by R rotations anticlockwise, and show the resulting matrix. | rotate_matrix.cpp|
| Rotate an array by r elements ( left or right ) | array_rotation.cpp
| Given an array of repeating/non-repeating intergeres, determine the first non-repeating int in this array | first*non*repeating_int.cpp|
| In Quantumland, there are n cities numbered from 1 to n. Here, c_{i} denotes the i^{th} city. There are n−1 roads in Quantumland. Here, c_{i} and c_{i+1} have a bidirectional road between them for each i < n.There is a rumor that Flatland is going to attack Quantumland, and the queen wants to keep her land safe. The road between c_{i} and c_{i+1} is safe if there is a guard in c_{i} or c_{i+1}. The queen has already placed a few guards in some of the cities, but she is not sure if they are enough to keep the roads safe. She wants to know the minimum number of new guards she needs to hire. See comments in solution for input/output details. | save_quantamland.cpp|
| You are given an integer N. Find the digits in this number that exactly divide N (division that leaves 0 as remainder) and display their count. For N=24, there are 2 digits (2 & 4). Both of these digits exactly divide 24. So our answer is 2. See more details in header comment of the solution file. | findDigits.cpp|
| Encrypt and then decrypts a text using Caeser Cipher. | caeser_cipher.cpp|
| Encrypt and then decrypts a text using Vigenère cipher. | vigenere_cipher.cpp|
| Generate binary numbers between 1 to N efficiently. |n_binary.cpp|
| Implement power function | power_function.cpp|

| Problem | Solution |
| :------------ | :----------: |
| Print all the permutations of a string. Example: Permutations of ABC are ABC, ACB, BCA, BAC, CAB, CBA | string_permutations.cpp |
| Euclidean algorithm to find greatest common divisor of two numbers. (Iterative and recursive)|gcd.cpp|
| Implement pow(x,y) using divide and conquer approach. Try implementing it in O(logn)| pow.cpp|
| Calculate factorial of large number, say 100 (it will have 158 digits) |factorial*of*large_num.cpp|
| Generate all possible words from a number entered on a traditional mobile keypad | phone_digits.cpp|
| Given a string representation of a number, remove n characters from the string such that number representation is lowest possible.| lowest*possible*number.cpp|
| Detect if a number is a happy number. A number is happy number if sequence of operations where number is replaced by sum of square of its digits leads eventually to 1. A number is not a happy number if we are in an infinite loop when above operations are performed.| happy_number.cpp|

| Problem | Solution |
| :------------ | :----------: |
| We have series of n daily price quotes for a stock. We need to calculate span of stock's price for all n days. Span for ith day is defined as maximum number of consecutive days, for which the price of the stock was less than or equal to ith day. For stock quotes {100, 60, 70, 65, 80, 85} span will be {1, 1, 2, 1, 4, 5}. Span for day 1 is always 1, now for day 2 stock is at 60, and there is no day befor it when stock was less than 60. So span remains 1. For day 3, the stock is priced at 70, so its span is 2, as previous day it was 60, and so on. | stock*span*problem.cpp |
| Given an infix expression, convert it to postfix expression, Example (A+B)*C --> AB+C* | infix*to*postfix.cpp |
| Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.| valid_parenthesis.cpp|

| Problem | Solution |
| :------------ | :----------: |
| Given a sorted vector, return first index of the occurrence of a value in vector, if number does not exist, return -1 | first*occurrence*binary_search.cpp |
| Find the first repeating element in an array of integers. Given an array of integers, find the first repeating element in it. We need to find the element that occurs more than once and whose index of first occurrence is smallest.| firstRepeatingElement.cpp|
| Given a list of unsorted integers, A={a_{1},a_{2},…,a_{N}}, Find the pair of elements that have the smallest absolute difference between them? If there are multiple pairs, find them all.| closest_numbers.cpp|
| Given a sorted array, determine index of fixed point in this array. If array does not have a fixed point return -1. An array has a fixed point when index of the element is same as index i.e. i == arr[i], Expected time complexity O(logn)| fixedPoint.cpp|
| Find the maximum element in an array which is first increasing and then decreasing. Input: arr[] = {8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1}, output : 500. Array may be strictly increasing or decreasing as well. ExpectedTime complexity is O(logn).| findMaximum.cpp|
| Given an array of positive and/or negative integers, find a pair in the array whose sum is closest to 0.| findClosestPairToZero.cpp|
| Numeros, the Artist, had two lists A and B, such that B was a permutation of A. Numeros was very proud of these lists. Unfortunately, while transporting them from one exhibition to another, some numbers were left out of A. Can you find the missing numbers? Notes:

- If a number occurs multiple times in the lists, you must ensure that the frequency of that number in both lists is the same. If that is not the case, then it is also a missing number.

- You have to print all the missing numbers in ascending order.

- Print each missing number once, even if it is missing multiple times.

- The difference between maximum and minimum number in B is less than or equal to 100.

- There will be four lines of input: n - the size of the first list, This is followed by n space-separated integers that make up the first list. m - the size of the second list. This is followed by m space-separated integers that make up the second list. Output the missing numbers in ascending order.| missingNumbers.cpp|
| Find the closest pair from two sorted arrays. Given two sorted arrays and a number x, find the pair whose sum is closest to x and the pair has an element from each array. We are given two arrays ar1[0…m-1] and ar2[0..n-1] and a number x, we need to find the pair ar1[i] + ar2[j] such that absolute value of (ar1[i] + ar2[j] – x) is minimum.| closestPairSorted.cpp|
| Given an array A of n elements, find three indices i, j and k such that A[i]^2 + A[j]^2 = A[K]^2. O(n2) time complexity and O(1) space complexity | squareSum.cpp|
| Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that sorting this subarray makes the whole array sorted. |minLengthUnsortedArray.cpp|
| Find the missing number in Arithmetic Progression | missingNumber2.cpp |
| Find the common elements in 3 sorted vectors | commonIn3Arrays.cpp |
| Find all the pairs with a given sum in an unsorted array/vector | find
*pairs*with_sum.cpp | | Given an array, find peak element in it. A peak element is an element that is greater than its neighbors.| peak_element.cpp | | Given a sorted array of distinct non-negative integers, find smallest missing element in it.| smallest_missing.cpp| | Move all zeros in the vector to the end | move_zeros.cpp|### Graph Problems

| Problem | Solution | | :------------ | :----------: | | Depth First Traversal of a Graph | dfsDemo.cpp | | Breadth First Traversal of a Graph | bfsDemo.cpp | | calculate the shortest distance from the start position (Node S) to all of the other nodes in the graph using Dijkstra algorithm. | dijkstra-shortest-reach.cpp| | Calculate total weight of Minimum Spanning Tree of a given graph ( sum of weights of edges which forms MST) using Prim's algorithm | primsMST.cpp| | Print Minimum Spanning Tree( MST ) of a given graph using Kruskal's algorithm.| kruskalMST.cpp| | Create a program to generate a Huffman encoding for each character as a table.|huffman_encoding.cpp| | Search a given word in a 2D board containing letters. The word can be constructed by sequentially traversing adjacent horizontal or vertical cells. In a sequence to form word, letter on same position can not be used more than once. (Check top of file for examples.)|grid

*word*search.cpp| | Given a 2D screen, location of the pixel and new value of the color to fill, replace the color of the pixel and all the adjacent(up, below, left, right) same colored pixel with new color. This is same as flood fill (remember the bucket symbol) a region in MS-PAINT.| flood_fill.cpp|### Greedy Problems

| Problem | Solution | | :------------ | :----------: | | Given two integer arrays, A and B, each containing N integers. You are free to permute the order of the elements in the arrays. Is there an permutation A', B' possible of A and B, such that, A'

_{i}+B'_{i}≥ K for all i, where A'_{i}denotes the i^{th}element in the array A' and B'_{i}denotes i^{th}element in the array B'.| two_arrays.cpp| | John is taking orders. The i^{th}order is placed by the i^{th}customer at t_{i}time and it takes d_{i}time to procees. What is the order in which the customers will get their orders? (see more details in solutions's comments)|orders_order.cpp|### Backtracking Problems

| Problem | Solution | | :------------ | :----------: | | You are given a digit string (e.g "1234", "567" etc), provide all possible letter combinations we could generate from this digit string, based on the mapping we see on the telphone/mobile dialpad. If you have typed SMS in old style phones, you would know. For e.g. "1" is mapped to "abc", 2 is mapped to "def". You can refer to the image..

- Example: "34" will give output: {"dg","dh","di","eg","eh","ei","fg","fh","fi"}

*'.*' Matches any sequence of character.- '?' Matches any single character.

- '

| Problem | Solution | | :------------ | :----------: | | Given a sorted integer array without duplicates, return the summary of its ranges. For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].| summary_ranges.cpp| | Given a 2D matrix, with following properties

- Integers in each row are sorted in ascending from left to right.

- Integers in each column are sorted in ascending from top to bottom.

- A = [2,3,1,1,4], return true.

- A = [3,2,1,0,4], return false.

- Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL

- Insert a character

- Delete a character.

- Replace a character

- Input: cccbbbbaa Output: bbbcccaa