Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

https://github.com/realpacific/algorithms

A collection of solutions to the data structure and algorithm problems
https://github.com/realpacific/algorithms

algorithms data-structures java kotlin leetcode

Last synced: 3 months ago
JSON representation

A collection of solutions to the data structure and algorithm problems

Lists

README

        

# algorithms :robot:

A collection of solution to the data structure and algorithm problems

[View web version](https://prashantbarahi.com.np/docs/algorithms/intro) | [View by tags](https://prashantbarahi.com.np/docs/tags/)

### Table of Contents

| Filename | Description |
| --- | --- |
| [InsertInterval](src/questions/InsertInterval.kt)
Kotlin • questions | You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the ith interval and intervals is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval.
Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary). Return `intervals` after the insertion.
[Source](https://leetcode.com/problems/insert-interval/)
|
| [MergeIntervals](src/questions/MergeIntervals.kt)
Kotlin • questions | Given an array of intervals where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
[Source](https://leetcode.com/problems/merge-intervals/)
|
| [WordSearch](src/questions/WordSearch.kt)
Kotlin • questions | Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
[Source](https://leetcode.com/problems/word-search)
|
| [ReorderList](src/questions/ReorderList.kt)
Kotlin • questions | You are given the head of a singly linked-list. The list can be represented as `L0 → L1 → … → Ln - 1 → Ln`
Reorder the list to be on the following form: `L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …` You may not modify the values in the list's nodes. Only nodes themselves may be changed.
[Source](https://leetcode.com/problems/reorder-list)
|
| [IntegerToRoman](src/questions/IntegerToRoman.kt)
Kotlin • questions | Given an integer, convert it to a roman numeral.
[Source](https://leetcode.com/problems/integer-to-roman/)
|
| [SpiralMatrixII](src/questions/SpiralMatrixII.kt)
Kotlin • questions | Given a positive integer n, generate an n x n matrix filled with elements from 1 to n^2 in spiral order.
|
| [SpiralMatrix](src/questions/SpiralMatrix.kt)
Kotlin • questions | Given an `m x n` matrix, return all elements of the `matrix` in spiral order.
[Source](https://leetcode.com/problems/spiral-matrix) – [Solution](https://leetcode.com/problems/spiral-matrix/discuss/20571/1-liner-in-Python-%2B-Ruby)
|
| [WordBreak](src/questions/WordBreak.kt)
Kotlin • questions | Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation.
[Source](https://leetcode.com/problems/word-break/) – [Solution](https://leetcode.com/problems/word-break/discuss/43790/Java-implementation-using-DP-in-two-ways)
|
| [GenerateParentheses](src/questions/GenerateParentheses.kt)
Kotlin • questions | Given `n` pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
[Source](https://leetcode.com/problems/generate-parentheses/)
|
| [SearchRange](src/questions/SearchRange.kt)
Kotlin • questions | Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1].
[Source](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/)
|
| [MinTotalInTriangle](src/questions/MinTotalInTriangle.kt)
Kotlin • questions | Given a triangle array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
[Source](https://leetcode.com/problems/triangle/)
|
| [CountAndSay](src/questions/CountAndSay.kt)
Kotlin • questions | The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
* `countAndSay(1)` = "1"
* `countAndSay(n)` is the way you would "say" the digit string from `countAndSay(n-1)`,which is then converted into a different digit string.
To determine how you "say" a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.
[Source](https://leetcode.com/problems/count-and-say/)
|
| [PalindromeInteger](src/questions/PalindromeInteger.kt)
Kotlin • questions | Write a function that checks whether an integer is a palindrome.
For example, 191 is a palindrome, as well as 111. 123 is not a palindrome.
|
| [SortLinkedList](src/questions/SortLinkedList.kt)
Kotlin • questions | Given the head of a linked list, return the list after sorting it in ascending order.
[Source](https://leetcode.com/problems/sort-list/)
|
| [CustomSortString](src/questions/CustomSortString.kt)
Kotlin • questions | You are given two strings order and s. All the words of order are unique and were sorted in some custom order previously. Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.
Return any permutation of s that satisfies this property.
[Source](https://leetcode.com/problems/custom-sort-string-kt/)
|
| [MinLengthAfterDeletingSimilarEnds](src/questions/MinLengthAfterDeletingSimilarEnds.kt)
Kotlin • questions | Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:

* Pick a non-empty prefix from the string s where all the characters in the prefix are equal.
* Pick a non-empty suffix from the string s where all the characters in this suffix are equal.
* The prefix and the suffix should not intersect at any index.
* The characters from the prefix and suffix must be the same.
* Delete both the prefix and the suffix.
Return the minimum length of s after performing the above operation any number of times (possibly zero times). [Source](https://leetcode.com/problems/min-length-after-deleting-similar-ends-kt/)
|
| [BinaryStringWithSubstringsRep1ToN](src/questions/BinaryStringWithSubstringsRep1ToN.kt)
Kotlin • questions | Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise. A substring is a contiguous sequence of characters within a string.
[Source](https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/)
|
| [DayOfTheYear](src/questions/DayOfTheYear.kt)
Kotlin • questions | Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.
[Source](https://leetcode.com/problems/day-of-the-year/)
|
| [KDiffPairs](src/questions/KDiffPairs.kt)
Kotlin • questions | Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:
* `0 <= i < j < nums.length`
* `abs(nums[i] - nums[j]) == k`
[Source](https://leetcode.com/problems/k-diff-pairs-in-an-array/)
|
| [ReversePolishNotation](src/questions/ReversePolishNotation.kt)
Kotlin • questions | You are given an array that contains an expression in Reverse Polish Notation. Return the result from evaluating the expression. You can assume the expression will always be valid.
Input - [“2”, “3”, “+”, “3”, “*”] Output - 15 because ( (2 + 3) * 3)
[Source](https://leetcode.com/problems/evaluate-reverse-polish-notation/)
|
| [RestoreIPAddresses](src/questions/RestoreIPAddresses.kt)
Kotlin • questions | A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.
[Source](https://leetcode.com/problems/restore-ip-addresses/)
|
| [ReverseWords](src/questions/ReverseWords.kt)
Kotlin • questions | You are given a character array containing a set of words separated by whitespace. Your task is to modify that character array so that the words all appear in reverse order. Do this without using any extra space. |
| [GeneratePermutations](src/handbook/GeneratePermutations.kt)
Kotlin • handbook | Given array of integers, generate its permutations. |
| [GenerateSubsets](src/handbook/GenerateSubsets.kt)
Kotlin • handbook | Bit method – Each subset of n elements can be represented as sequences of n bits
Backtrack method
|
| [UniquePathsII](src/questions/UniquePathsII.kt)
Kotlin • questions | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and space is marked as 1 and 0 respectively in the grid.

[Source](https://leetcode.com/problems/unique-paths-ii/)
|
| [SingleElementInSortedArray](src/questions/SingleElementInSortedArray.kt)
Kotlin • questions | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element that appears only once. Your solution must run in `O(log n)` time and `O(1)` space.
[Source](https://leetcode.com/problems/single-element-in-a-sorted-array/)
|
| [UniquePaths](src/questions/UniquePaths.kt)
Kotlin • questions | A robot is located in the top-left corner of a `m x n` grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?
[Source](https://leetcode.com/problems/unique-paths/)
|
| [RotateImage](src/questions/RotateImage.kt)
Kotlin • questions | You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
[Source](https://leetcode.com/problems/rotate-image-/)
|
| [LargestDivisibleSubset](src/questions/LargestDivisibleSubset.kt)
Kotlin • questions | Given a set of distinct positive integers nums, return the largest subset answer such that every pair (`answer[i]`, `answer[j]`) of elements in this subset satisfies:
`answer[i] % answer[j] == 0`, or `answer[j] % answer[i] == 0` If there are multiple solutions, return any of them.
[Source](https://leetcode.com/problems/largest-divisible-subset/)
@see LongestIncreasingSubSeq
@see LengthOfLongestIncreasingSubSeq
|
| [LongestIncreasingSubSeq](src/questions/LongestIncreasingSubSeq.kt)
Kotlin • questions | Given an integer array nums, return the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements.
[Explanation](https://youtu.be/mouCn3CFpgg?t=1057)
@see LengthOfLongestIncreasingSubSeq
|
| [LengthOfLongestIncreasingSubSeq](src/questions/LengthOfLongestIncreasingSubSeq.kt)
Kotlin • questions | Given an integer array nums, return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements.
[Source](https://leetcode.com/problems/longest-increasing-subsequence/) | [Explanation](https://www.youtube.com/watch?v=mouCn3CFpgg)
@see LongestIncreasingSubSeq
|
| [PivotIndex](src/questions/PivotIndex.kt)
Kotlin • questions | Calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. Return the leftmost pivot index. If no such index exists, return -1. [Source](https://leetcode.com/problems/pivot-index/) |
| [IteratorForCombination](src/questions/IteratorForCombination.kt)
Kotlin • questions | Design the CombinationIterator class:

* CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
* next() Returns the next combination of length combinationLength in lexicographical order.
* hasNext() Returns true if and only if there exists a next combination.
[Source](https://leetcode.com/problems/iterator-for-combination/)
|
| [BuddyString](src/questions/BuddyString.kt)
Kotlin • questions | Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.
[Source](https://leetcode.com/problems/buddy-strings/)
|
| [DegreeOfAnArray](src/questions/DegreeOfAnArray.kt)
Kotlin • questions | Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
[Source](https://leetcode.com/problems/degree-of-an-array/)
|
| [DailyTemperatures](src/questions/DailyTemperatures.kt)
Kotlin • questions | Given an array of integers `temperatures` represents the daily temperatures, return an array answer such that `answer[i]` is the number of days you have to wait after the `ith` day to get a warmer temperature. If there is no future day for which this is possible, keep `answer[i] == 0` instead.
[Source](https://leetcode.com/problems/daily-temperatures/)
|
| [CanPlaceFlowers](src/questions/CanPlaceFlowers.kt)
Kotlin • questions | You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.
[Source](https://leetcode.com/problems/can-place-flowers/)
|
| [DesignSkipList](src/questions/DesignSkipList.kt)
Kotlin • questions |
[Source](https://leetcode.com/problems/design-skiplist/) – [Gist](https://www.youtube.com/watch?v=UGaOXaXAM5M)
|
| [DesignHashMap](src/questions/DesignHashMap.kt)
Kotlin • questions | Design a HashMap without using any built-in hash table libraries:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.
* `int get(int key)` returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
* `void remove(key)` removes the key and its corresponding value if the map contains the mapping for the key.
[Source](https://leetcode.com/problems/design-hashmap/)
@see MyHashSet
|
| [DesignHashset](src/questions/DesignHashset.kt)
Kotlin • questions | Implement MyHashSet class:
* `void add(key)` Inserts the value key into the HashSet.
* `bool contains(key)` Returns whether the value key exists in the HashSet or not.
* `void remove(key)` Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.
[Source](https://leetcode.com/problems/design-hashset/)
@see MyHashMap
|
| [ReshapeTheMatrix](src/questions/ReshapeTheMatrix.kt)
Kotlin • questions | You are given an `m x n` matrix `mat` and two integers `r` and `c` representing the number of rows and the number of columns of the wanted reshaped matrix. The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
[Source](https://leetcode.com/problems/reshape-the-matrix/)
|
| [NumberOf1Bits](src/questions/NumberOf1Bits.kt)
Kotlin • questions | Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). [Source](https://leetcode.com/problems/number-of-1-bits/) |
| [SymmetricTree](src/questions/SymmetricTree.kt)
Kotlin • questions | Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
[Source](https://leetcode.com/problems/symmetric-tree/)
|
| [LinkedListCycle](src/questions/LinkedListCycle.kt)
Kotlin • questions | Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
[Source](https://leetcode.com/problems/linked-list-cycle-kt/)
|
| [ReverseStringII](src/questions/ReverseStringII.kt)
Kotlin • questions | Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting from the start of the string.
If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and left the other as original.
[Source](https://leetcode.com/problems/reverse-string-ii/)
|
| [LongestAbsoluteFilePath](src/questions/LongestAbsoluteFilePath.kt)
Kotlin • questions | Suppose we have a file system that stores both files and directories.
Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s.
Given a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0.
[Source](https://leetcode.com/problems/longest-absolute-file-path/)
|
| [ArrangingCoins](src/questions/ArrangingCoins.kt)
Kotlin • questions | You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `i`th row has exactly `i` coins. The last row of the staircase may be incomplete. Given the integer n, return the number of complete rows of the staircase you will build.
[Source](https://leetcode.com/problems/arranging-coins/)
|
| [SimplifiedFraction](src/questions/SimplifiedFraction.kt)
Kotlin • questions | Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. The fractions can be in any order.
[Source](https://leetcode.com/problems/simplified-fractions/)
|
| [ConvertToHex](src/questions/ConvertToHex.kt)
Kotlin • questions | Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used. All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself. [Source](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) – [solution](https://leetcode.com/problems/convert-a-number-to-hexadecimal/discuss/824192/Java-100-Time-with-Detailed-Explanation) |
| [SumRootToLeafNumber](src/questions/SumRootToLeafNumber.kt)
Kotlin • questions | You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number. For example, the root-to-leaf path `1 -> 2 -> 3` represents the number 123. Return the total sum of all root-to-leaf numbers.
[Source](https://leetcode.com/problems/sum-root-to-leaf-numbers/)
|
| [FindDuplicateNumber](src/questions/FindDuplicateNumber.kt)
Kotlin • questions | Given an array of integers nums containing `n + 1` integers where each integer is in the range `[1, n]` inclusive. There is only one repeated number in `nums`, return this repeated number. You must solve the problem without modifying the array nums and uses only constant extra space.
[Source](https://leetcode.com/problems/find-the-duplicate-number/)
|
| [Sqrtx](src/questions/Sqrtx.kt)
Kotlin • questions | Given a non-negative integer x, compute and return the square root of x. [Source](https://leetcode.com/problems/sqrtx/) |
| [SetMismatch](src/questions/SetMismatch.kt)
Kotlin • questions | You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. Find the number that occurs twice and the number that is missing and return them in the form of an array. [Source](https://leetcode.com/problems/set-mismatch/) |
| [IntersectionOfTwoArrays](src/questions/IntersectionOfTwoArrays.kt)
Kotlin • questions | Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
[Source](https://leetcode.com/problems/intersection-of-two-arrays/)
|
| [ReverseWordsInStringIII](src/questions/ReverseWordsInStringIII.kt)
Kotlin • questions | Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
[Source](https://leetcode.com/problems/reverse-words-in-a-string-iii/)
|
| [SurroundedRegions](src/questions/SurroundedRegions.kt)
Kotlin • questions | Given an `m x n` matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region.
[Source](https://leetcode.com/problems/surrounded-regions/)
|
| [DiameterOfBinaryTree](src/questions/DiameterOfBinaryTree.kt)
Kotlin • questions | Given the root of a binary tree, return the length of the diameter of the tree. The 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.
[Source](https://leetcode.com/problems/diameter-of-binary-tree/) – [solution](https://leetcode.com/problems/diameter-of-binary-tree/discuss/101132/Java-Solution-MaxDepth)
|
| [SumOfLeftLeaves](src/questions/SumOfLeftLeaves.kt)
Kotlin • questions | Given the root of a binary tree, return the sum of all left leaves.
[Source](https://leetcode.com/problems/sum-of-left-leaves/)
|
| [CountingBits](src/questions/CountingBits.kt)
Kotlin • questions | Given an integer `n`, return an array `ans` of length `n + 1` such that for each `i` (0 <= i <= n), `ans[i]` is the number of 1's in the binary representation of `i`.
[Source](https://leetcode.com/problems/counting-bits/)
|
| [WildcardSearchDS](src/questions/WildcardSearchDS.kt)
Kotlin • questions | Design a data structure that supports adding new words and finding if a string matches any previously added string. Your data structure should implement two methods
* `addWord(word)`- Adds word to the data structure
* `searchWorld(word)`- Returns true if there is any string in the data structure that matches word. Word may contain dots where a dot can be matched with any letter (a dot represents a wildcard).
|
| [NimGame](src/questions/NimGame.kt)
Kotlin • questions | You are playing the following Nim Game with your friend:

* Initially, there is a heap of stones on the table.
* You and your friend will alternate taking turns, and you go first.
* On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
* The one who removes the last stone is the winner.
Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.
[Source](https://leetcode.com/problems/nim-game/) – [Solution](https://leetcode.com/problems/nim-game/discuss/73749/Theorem:-all-4s-shall-be-false)
|
| [ContainsDuplicateII](src/questions/ContainsDuplicateII.kt)
Kotlin • questions | Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that `nums[i] == nums[j]` and `abs(i - j) <= k`.
[Source](https://leetcode.com/problems/contains-duplicate-ii/)
|
| [ExcelSheetColumnTitle](src/questions/ExcelSheetColumnTitle.kt)
Kotlin • questions | Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. `A -> 1, B -> 2, C -> 3, Z -> 26, AA -> 27, AB -> 28`
[Source](https://leetcode.com/problems/excel-sheet-column-title/)
|
| [ReverseBits](src/questions/ReverseBits.kt)
Kotlin • questions | Reverse bits of a given 32 bits unsigned integer. [Source](https://leetcode.com/problems/reverse-bits/) – [Solution](https://leetcode.com/problems/reverse-bits/discuss/54746/Java-Solution-and-Optimization) |
| [MinStack](src/questions/MinStack.kt)
Kotlin • questions | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. [Source](https://leetcode.com/problems/min-stack/) |
| [longest_palindrome](python/longest_palindrome.py)
Python • python | |
| [RepeatedSubstringPattern](src/questions/RepeatedSubstringPattern.kt)
Kotlin • questions | Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. [Source](https://leetcode.com/problems/repeated-substring-pattern/) - [Solution](https://leetcode.com/problems/repeated-substring-pattern/discuss/94334/Easy-python-solution-with-explaination) |
| [CountCompleteTreeNode](src/questions/CountCompleteTreeNode.kt)
Kotlin • questions | Given the root of a complete binary tree, return the number of the nodes in the tree. Every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. [Source](https://leetcode.com/problems/count-complete-tree-nodes/) |
| [AddBinary](src/questions/AddBinary.kt)
Kotlin • questions | Given two binary strings a and b, return their sum as a binary string. [Source](https://leetcode.com/problems/add-binary/) |
| [BestTimeStockII](src/questions/BestTimeStockII.kt)
Kotlin • questions | You are given an integer array prices where `prices[i]` is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. Find and return the maximum profit you can achieve.
[Source](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)
@see [BestTimeStock]
|
| [IsSubsequence](src/questions/IsSubsequence.kt)
Kotlin • questions | Given two strings s and t, return true if s is a subsequence of t, or false otherwise. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. [Source](https://leetcode.com/problems/is-subsequence/) |
| [BestTimeStock](src/questions/BestTimeStock.kt)
Kotlin • questions | You are given an array prices where `prices[i]` is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
[Source](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) @see [BestTimeStockII]
|
| [TotalHammingDistance](src/questions/TotalHammingDistance.kt)
Kotlin • questions | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums. [Source](https://leetcode.com/problems/total-hamming-distance/) |
| [HammingDistance](src/questions/HammingDistance.kt)
Kotlin • questions | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them. [Source](https://leetcode.com/problems/hamming-distance/) |
| [MaxAreaOfIsland](src/questions/MaxAreaOfIsland.kt)
Kotlin • questions | You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Return the maximum area of an island in grid. If there is no island, return 0. [Source](https://leetcode.com/problems/max-area-of-island) |
| [MinIndexOfSumLists](src/questions/MinIndexOfSumLists.kt)
Kotlin • questions | Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer. [Source](https://leetcode.com/problems/minimum-index-sum-of-two-lists/) |
| [MoveZeroes](src/questions/MoveZeroes.kt)
Kotlin • questions | Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. [Source](https://leetcode.com/problems/move-zeroes/) |
| [MissingNumber](src/questions/MissingNumber.kt)
Kotlin • questions | Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. [Source](https://leetcode.com/problems/missing-number/) |
| [ArrayPartitionI](src/questions/ArrayPartitionI.kt)
Kotlin • questions | Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum. [Source](https://leetcode.com/problems/array-partition-i/) |
| [IslandPerimeter](src/questions/IslandPerimeter.kt)
Kotlin • questions | You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100.
Determine the perimeter of the island.
[Source](https://leetcode.com/problems/island-perimeter/)
|
| [MaxSubarray](src/questions/MaxSubarray.kt)
Kotlin • questions | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. [Source](https://leetcode.com/problems/maximum-subarray/) – [Solution](https://leetcode.com/problems/maximum-subarray/discuss/20396/Easy-Python-Way) |
| [MaxProductSubArray](src/questions/MaxProductSubArray.kt)
Kotlin • questions | Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. [Source](https://leetcode.com/problems/maximum-product-subarray/) – [Solution](https://leetcode.com/problems/maximum-product-subarray/discuss/48302/2-Passes-scan-beats-99) |
| [MergeSortedLists](src/questions/MergeSortedLists.kt)
Kotlin • questions | Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. [Source](https://leetcode.com/problems/merge-two-sorted-lists/) |
| [KeyboardRow](src/questions/KeyboardRow.kt)
Kotlin • questions | Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard. [Source](https://leetcode.com/problems/keyboard-row/) |
| [SwapAdjacentNodes](src/questions/SwapAdjacentNodes.kt)
Kotlin • questions | Given a linked list, swap every two adjacent nodes and return its head.
1 -> 2 -> 3 -> 4 -----> 2 -> 1 -> 4 -> 3
|
| [RandomizedSet](src/questions/RandomizedSet.kt)
Kotlin • questions | Implement the RandomizedSet class:
* `RandomizedSet()` Initializes the RandomizedSet object.
* `bool insert(int val)` Inserts an item val into the set if not present. Returns true if not present, false otherwise.
* `bool remove(int val)` Removes an item val from the set if present. Returns true if the item was present, false otherwise.
* `int getRandom()` Returns a random element from the current set of elements. [Source](https://leetcode.com/problems/insert-delete-getrandom-o1/)
|
| [ClimbingStairs](src/questions/ClimbingStairs.kt)
Kotlin • questions | You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? [Source](https://leetcode.com/problems/climbing-stairs/) |
| [FirstUniqueCharacter](src/questions/FirstUniqueCharacter.kt)
Kotlin • questions | Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. [Source](https://leetcode.com/problems/first-unique-character-kt/) |
| [TopKFrequent](src/questions/TopKFrequent.kt)
Kotlin • questions | Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. [Source](https://leetcode.com/problems/top-k-frequent-elements//) |
| [ContainsDuplicate](src/questions/ContainsDuplicate.kt)
Kotlin • questions | Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. [Source](https://leetcode.com/problems/contains-duplicate/) |
| [SortCharByFrequency](src/questions/SortCharByFrequency.kt)
Kotlin • questions | Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string. Return the sorted string. If there are multiple answers, return any of them. [Source](https://leetcode.com/problems/sort-characters-by-frequency/) |
| [RangeSumQuery](src/questions/RangeSumQuery.kt)
Kotlin • questions | Given an integer array nums, handle multiple queries of the following type: Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. [Source](https://leetcode.com/problems/range-sum-query-immutable/) |
| [RangeSumQueryMutable](src/questions/RangeSumQueryMutable.kt)
Kotlin • questions | Given an integer array nums, handle multiple queries of the following types:
* Update the value of an element in nums.
* Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
[Source](https://leetcode.com/problems/range-sum-query-mutable/)
|
| [NextGreaterElementII](src/questions/NextGreaterElementII.kt)
Kotlin • questions | Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums. The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.
[Source](https://leetcode.com/problems/next-greater-element-ii/)
|
| [NextGreaterElement](src/questions/NextGreaterElement.kt)
Kotlin • questions | The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2 and all are unique.
For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.
[Source](https://leetcode.com/problems/next-greater-element-i/)
|
| [MinDeletionUniqueFrequency](src/questions/MinDeletionUniqueFrequency.kt)
Kotlin • questions | Minimum Deletions to Make Character Frequencies Unique
A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good.
[Source](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/) – [Solution](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/1107954/Java-Simple-Solution)
|
| [PascalTriangleII](src/questions/PascalTriangleII.kt)
Kotlin • questions | Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.
@see pascalTriangle [Source](https://leetcode.com/problems/pascals-triangle-ii/)
|
| [PascalTriangle](src/questions/PascalTriangle.kt)
Kotlin • questions | Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
[Source](https://leetcode.com/problems/pascals-triangle/)
|
| [CousinsBinaryTree](src/questions/CousinsBinaryTree.kt)
Kotlin • questions | Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.
Two nodes of a binary tree are cousins if they have the same depth with different parents.
[Source](https://leetcode.com/problems/cousins-in-binary-tree/)
|
| [RansomNote](src/questions/RansomNote.kt)
Kotlin • questions | Given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote.
[Source](https://leetcode.com/problems/ransom-note-kt/)
|
| [UglyNumber](src/questions/UglyNumber.kt)
Kotlin • questions | An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return true if n is an ugly number. [Source](https://leetcode.com/problems/ugly-number/) |
| [RegionsCutBySlashes](src/questions/RegionsCutBySlashes.kt)
Kotlin • questions | An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions. Given the grid `grid` represented as a string array, return the number of regions. Note that backslash characters are escaped, so a '\' is represented as '\\'.
[Explanation](https://www.youtube.com/watch?v=Wafu5vOxPRE) – [Source](https://leetcode.com/problems/regions-cut-by-slashes/)
|
| [forward_sum_of_nodes](python/codinginterview/forward_sum_of_nodes.py)
Python • codinginterview | (6 -> 1 -> 7) + (2 -> 9). That is 617 + 029 = 6 -> 4 -> 6 |
| [find_intersection_linked_list](python/codinginterview/find_intersection_linked_list.py)
Python • codinginterview | Find intersection between two linked list |
| [DetectCapital](src/questions/DetectCapital.kt)
Kotlin • questions | We define the usage of capitals in a word to be right when one of the following cases holds:
* All letters in this word are capitals, like "USA".
* All letters in this word are not capitals, like "leetcode".
* Only the first letter in this word is capital, like "Google".
Given a string word, return true if the usage of capitals in it is right.
[Source](https://leetcode.com/problems/detect-capital/)
|
| [ReverseVowel](src/questions/ReverseVowel.kt)
Kotlin • questions | Given a string s, reverse only all the vowels in the string and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.
[Source](https://leetcode.com/problems/reverse-vowels-of-a-string/)
|
| [StackUsingQueues](src/questions/StackUsingQueues.kt)
Kotlin • questions | Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
[Source](https://leetcode.com/problems/implement-stack-using-queues/)
|
| [ReverseString](src/questions/ReverseString.kt)
Kotlin • questions | Write a function that reverses a string. The input string is given as an array of characters s. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
[Source](https://leetcode.com/problems/reverse-string/)
|
| [FirstBadVersion](src/questions/FirstBadVersion.kt)
Kotlin • questions | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Constraint `1 <= bad <= n <= 2^31 - 1`
[Source](https://leetcode.com/problems/first-bad-version/)
|
| [ValidAnagram](src/questions/ValidAnagram.kt)
Kotlin • questions | Given two strings s and t, return true if t is an anagram of s, and false otherwise.
[Source](https://leetcode.com/problems/valid-anagram/)
|
| [FindAllAnagrams](src/questions/FindAllAnagrams.kt)
Kotlin • questions | Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
[Source](https://leetcode.com/problems/find-all-anagrams-in-a-string/)
|
| [LongestPalindrome](src/questions/LongestPalindrome.kt)
Kotlin • questions | Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
[Source](https://leetcode.com/problems/longest-palindrome/)
|
| [SummaryRanges](src/questions/SummaryRanges.kt)
Kotlin • questions | You are given a sorted unique integer array nums.
Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.
Each range [a,b] in the list should be output as:
*"a->b" if a != b
* "a" if a == b
[Source](https://leetcode.com/problems/summary-ranges/)
|
| [SameTree](src/questions/SameTree.kt)
Kotlin • questions | Given the roots of two binary trees p and q, write a function to check if they are the same or not.
[Source](https://leetcode.com/problems/same-tree/)
|
| [BSTFromPreorder](src/questions/BSTFromPreorder.kt)
Kotlin • questions | Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. A preorder traversal of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`.
[Source](https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/)
|
| [WordPattern](src/questions/WordPattern.kt)
Kotlin • questions | Given a pattern and a string s, find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
[Source](https://leetcode.com/problems/word-pattern/)
|
| [PowerOf4](src/questions/PowerOf4.kt)
Kotlin • questions | Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x.
[Source](https://leetcode.com/problems/power-of-four)
|
| [LicenseKeyFormatting](src/questions/LicenseKeyFormatting.kt)
Kotlin • questions | You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k. We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key.
[Source](https://leetcode.com/problems/license-key-formatting/)
|
| [HappyNumber](src/questions/HappyNumber.kt)
Kotlin • questions | Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process:
* Starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy.
[Source](https://leetcode.com/problems/happy-number)
|
| [MaxDepthOfBinaryTree](src/questions/MaxDepthOfBinaryTree.kt)
Kotlin • questions | Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
[Source](https://leetcode.com/problems/maximum-depth-of-binary-tree/)
|
| [AssignCookies](src/questions/AssignCookies.kt)
Kotlin • questions | Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.
[Source](https://leetcode.com/problems/assign-cookies/)
|
| [MajorityElement](src/questions/MajorityElement.kt)
Kotlin • questions | Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
[Source](https://leetcode.com/problems/majority-element/)
|
| [TwoSumII](src/questions/TwoSumII.kt)
Kotlin • questions | Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Return the indices of the two numbers, index1 and index2, as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
[Source](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)
|
| [AddStrings](src/questions/AddStrings.kt)
Kotlin • questions | Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
[Source](https://leetcode.com/problems/add-strings/)
|
| [ThirdMaximumNumber](src/questions/ThirdMaximumNumber.kt)
Kotlin • questions | Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number. |
| [FindTheDifference](src/questions/FindTheDifference.kt)
Kotlin • questions | You are given two strings s and t. String t is generated by random shuffling string s and then add one more letter at a random position. Return the letter that was added to t.
[Source](https://leetcode.com/problems/find-the-difference/)
|
| [ValidPalindrome](src/questions/ValidPalindrome.kt)
Kotlin • questions | Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. |
| [SingleNumber](src/questions/SingleNumber.kt)
Kotlin • questions | Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space.
[Source](https://leetcode.com/problems/single-number/)
|
| [IsomorphicStrings](src/questions/IsomorphicStrings.kt)
Kotlin • questions | Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
[Source](https://leetcode.com/problems/isomorphic-strings/)
|
| [SingleNumberII](src/questions/SingleNumberII.kt)
Kotlin • questions | Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.
[Source](https://leetcode.com/problems/single-number-ii/)
|
| [SingleNumberIII](src/questions/SingleNumberIII.kt)
Kotlin • questions | Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.
[Source](https://leetcode.com/problems/single-number-iii/)
|
| [PathSum](src/questions/PathSum.kt)
Kotlin • questions | Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. |
| [PlusOne](src/questions/PlusOne.kt)
Kotlin • questions | You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits.
[Source](https://leetcode.com/problems/plus-one/)
|
| [RemoveDuplicatesFromSortedList](src/questions/RemoveDuplicatesFromSortedList.kt)
Kotlin • questions | Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
[source](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)
|
| [LengthOfLastWord](src/questions/LengthOfLastWord.kt)
Kotlin • questions | Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only.
[Source](https://leetcode.com/problems/length-of-last-word)
|
| [RomanToInteger](src/questions/RomanToInteger.kt)
Kotlin • questions | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. I = 1, V=5, X = 10, L = 50, C = 100, D = 500, M = 1000
For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

* I can be placed before V (5) and X (10) to make 4 and 9.
* X can be placed before L (50) and C (100) to make 40 and 90.
* C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
|
| [DivideTwoIntegers](src/questions/DivideTwoIntegers.kt)
Kotlin • questions | Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. Return the quotient after dividing dividend by divisor. The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For this problem, assume that your function returns 2^31 − 1 when the division result overflows.
https://leetcode.com/problems/divide-two-integers/
|
| [ThreeSumClosest](src/questions/ThreeSumClosest.kt)
Kotlin • questions | Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers.
[Source](https://leetcode.com/problems/3sum-closest/)
|
| [LetterCombinationsOfPhoneNumber](src/questions/LetterCombinationsOfPhoneNumber.kt)
Kotlin • questions | Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

[Source](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)
|
| [MergeTwoSortedList](src/questions/MergeTwoSortedList.kt)
Kotlin • questions | Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. |
| [MaxNumberOfBalloons](src/questions/MaxNumberOfBalloons.kt)
Kotlin • questions | Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. You can use each character in text at most once. Return the maximum number of instances that can be formed.
Input: text = "nlaebolko"; Output: 1
[Source](https://leetcode.com/explore/item/3973)
|
| [ContainerWithMostWater](src/questions/ContainerWithMostWater.kt)
Kotlin • questions | Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. [Source](https://leetcode.com/problems/container-with-most-water/) |
| [ZigZagConversion](src/questions/ZigZagConversion.kt)
Kotlin • questions | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" [Source](https://leetcode.com/problems/zigzag-conversion/) |
| [LongestCommonPrefix](src/questions/LongestCommonPrefix.kt)
Kotlin • questions | Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". |
| [SearchInsertPosition](src/questions/SearchInsertPosition.kt)
Kotlin • questions | Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity.
[Source](https://leetcode.com/problems/search-insert-position/)
|
| [RemoveDuplicateFromSortedArray](src/questions/RemoveDuplicateFromSortedArray.kt)
Kotlin • questions | Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place. The relative order of the elements should be kept the same. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums.
[Source](https://leetcode.com/problems/remove-duplicates-from-sorted-array/submissions/)
|
| [BreadthFirstTraversal](src/algorithmdesignmanualbook/graph/BreadthFirstTraversal.kt)
Kotlin • graph | |
| [FindTransitionIndex](src/algorithmdesignmanualbook/sorting/FindTransitionIndex.kt)
Kotlin • sorting | Given unbounded 0s followed by unbounded number of 1s, find the first index of transition.
Done using ONE-SIDED BINARY SEARCH
Solution:
Incremental search 1,2,4,6,8... and then binary search on transition range
|
| [FindNumberOfOccurrence](src/algorithmdesignmanualbook/sorting/FindNumberOfOccurrence.kt)
Kotlin • sorting | Find the range in which [str] occurs in [array].
[Solution here](https://tutorialspoint.dev/algorithm/searching-algorithms/count-number-of-occurrences-or-frequency-in-a-sorted-array)
|
| [ArrangeNegativeThenPositiveNumber](src/algorithmdesignmanualbook/sorting/ArrangeNegativeThenPositiveNumber.kt)
Kotlin • sorting | 4-20 Rearrange an array of n keys so that all the negative keys precede all the nonnegative keys |
| [FastMedian](src/algorithmdesignmanualbook/sorting/FastMedian.kt)
Kotlin • sorting | NO need to sort all the items. Just find the sort the items before the median index Using quicksort, find the partition. Then throw away the left partition if the median index lies in the right portion while calibrating the new median index.
Similar to finding the kth smallest item in the unsorted list
|
| [is_linked_list_circular](python/codinginterview/is_linked_list_circular.py)
Python • codinginterview | Detect if a Linked List is circular |
| [one_or_zero_edits_away](python/codinginterview/one_or_zero_edits_away.py)
Python • codinginterview | 199. One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit(or zero edits) away. |
| [is_palindrome_permutation](python/codinginterview/is_palindrome_permutation.py)
Python • codinginterview | 195. Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. |
| [is_linked_list_palindrome](python/codinginterview/is_linked_list_palindrome.py)
Python • codinginterview | Check if a linked list is a palindrome |
| [sum_of_nodes_of_linked_list](python/codinginterview/sum_of_nodes_of_linked_list.py)
Python • codinginterview | Sum value of nodes 7 -> 1 -> 6 + 5 -> 9 -> 2 = 617+295 = 2 -> 1 -> 9 |
| [KDTree](src/algorithmsinanutshell/spatialtree/KDTree.kt)
Kotlin • spatialtree | K-d tree is a binary search tree with more than 1 dimensions (i.e k dimensions).
A 2-d tree looks like given points ((3, 6), (17, 15), (13, 15), (6, 12), (9, 1), (2, 7), (10, 19))
(3, 6) ----> compare x coordinate / \ (2,7) (17, 15) ----y compare y / \ (6,12) (13,15) ----x compare x \ / (9,1) (10,19) ----y
At each level, the dimensions of points are compared in alternating manner.
|
| [KnapSack01](src/algorithmsinanutshell/spatialtree/KnapSack01.kt)
Kotlin • spatialtree | Knapsack Problem: Given total capacity [totalCapacity] of a bag, how can you select subset of items of weight [weights] with profit [profits] such that the profit is maximized?
[Video](https://www.youtube.com/watch?v=8LusJS5-AGo)

! P ! w ! 0 ! 1 ! 2 ! 3 ! 4 ! 5 ! 6 ! 7 !
! 1 ! 1 ! ! ! ! ! ! ! ! !
! 4 ! 3 ! ! ! ! ! ! ! ! ! <-- while here, everything below are ignored so w1 and w3 are considered
! 5 ! 4 ! ! ! ! ! ! ! ! !
! 6 ! 5 ! ! ! ! ! ! ! ! !
|
| [NearestNeighbourQueries](src/algorithmsinanutshell/spatialtree/NearestNeighbourQueries.kt)
Kotlin • spatialtree | Given a target T and a set of points S, find the nearest neighbour of T in S.
https://www.youtube.com/watch?v=Glp7THUpGow
https://www.youtube.com/watch?v=XG4zpiJAkD4
https://www.cs.cmu.edu/~ckingsf/bioinfo-lectures/kdtrees.pdf
|
| [QuadTree](src/algorithmsinanutshell/spatialtree/QuadTree.kt)
Kotlin • spatialtree | https://algs4.cs.princeton.edu/92search/QuadTree.java.html
https://www.youtube.com/watch?v=jxbDYxm-pXg
https://www.youtube.com/watch?v=xFcQaig5Z2A
|
| [IntersectionOfLines](src/algorithmsinanutshell/IntersectionOfLines.kt)
Kotlin • algorithmsinanutshell | Two lines (P1, P2) and (P3,P4) intersect when orientation of:
* (P1 wrt P3,P4) and (P2 wrt P3,P4)
* (P3 wrt P1,P2) and (P4 wrt P1,P2)
are different.
A line (P1, P2) can be represented as vector P1P2 and orientation is the way (whether counter-clockwise or clockwise) direction it makes fromTo move from P1P2 fromTo P3.
P3 o
P1 o----->---o P2
orientation of P3 wrt P1P2 is ACW.
Special case is when (P1, P2) and (P3,P4) are collinear.

* In case of non-intersecting case, orientation is 0 for both P3(P1P2) and P4(P1,P2) and vv.
P1 o----->---o P2 P3 o----->---o P4 (Non-intersecting case)

* In case of intersecting case, orientation is different for both P3(P1P2) and P4(P1,P2) and vv.
P1 o----->--oP3-----P2o-->---o P4 (Intersecting case)
[Link](https://www.youtube.com/watch?v=bbTqI0oqL5U)
|
| [ConvexHullScanUsingGrahamScan](src/algorithmsinanutshell/ConvexHullScanUsingGrahamScan.kt)
Kotlin • algorithmsinanutshell | Find Convex Hull - a polygon that surrounds all points
[link](https://www.cs.auckland.ac.nz/software/AlgAnim/convex_hull.html)
|
| [OrientationOf3Points](src/algorithmsinanutshell/OrientationOf3Points.kt)
Kotlin • algorithmsinanutshell | [Link](https://www.geeksforgeeks.org/orientation-3-ordered-points/)
[Related](https://youtu.be/bbTqI0oqL5U?t=161)
|
| [LineSweepAlgorithm](src/algorithmsinanutshell/LineSweepAlgorithm.kt)
Kotlin • algorithmsinanutshell | Given a number of lines, find the lines that intersects with each other
Starting from left, sweep a vertical line through each point. Find the intersection of lines with each other that the vertical lines touches. If the sweep line has moved past a line (both points are to its left), this can be ignored.
[link](https://www.geeksforgeeks.org/given-a-set-of-line-segments-find-if-any-two-segments-intersect/)
|
| [Network](src/algorithmsinanutshell/networkflow/Network.kt)
Kotlin • networkflow | |
| [FordFulkersonAlgorithm](src/algorithmsinanutshell/networkflow/FordFulkersonAlgorithm.kt)
Kotlin • networkflow | Algorithm to find the max flow to the sink in a given [network]
https://brilliant.org/wiki/ford-fulkerson-algorithm/
https://www.youtube.com/watch?v=NwenwITjMys
O(E*mf) where E=edge, mf=value of max flow
|
| [FloydWarshallAlgorithm](src/algorithmsinanutshell/FloydWarshallAlgorithm.kt)
Kotlin • algorithmsinanutshell | # All pair shortest path algorithm
While Dijkstra Shortest Path algorithm helps find shortest path between start and end vertex, [FloydWarshallAlgorithm] finds the shortest path between all vertices in a [graph]
[Source](https://www.youtube.com/watch?v=oNI0rf2P9gE)
|
| [PrimMinSpanningTreeAlgorithm](src/algorithmsinanutshell/PrimMinSpanningTreeAlgorithm.kt)
Kotlin • algorithmsinanutshell | Prim Algorithm starts from min cost edge and then selects the next small cost edge while maintaining the connection with first edge.
This can be modeled using [PriorityQueue] sorted using [Edge] w.r.t its weight
|
| [TreeTraversal](src/algorithmsinanutshell/TreeTraversal.kt)
Kotlin • algorithmsinanutshell | |
| [GraphTraversal](src/algorithmsinanutshell/GraphTraversal.kt)
Kotlin • algorithmsinanutshell | Depth First Traversal
Breadth First Traversal
|
| [DijkstraAlgorithm](src/algorithmsinanutshell/DijkstraAlgorithm.kt)
Kotlin • algorithmsinanutshell | |
| [Graph](src/algorithmsinanutshell/Graph.kt)
Kotlin • algorithmsinanutshell | |
| [GreatestCommonDivisor](src/algorithmsinanutshell/GreatestCommonDivisor.kt)
Kotlin • algorithmsinanutshell | Greatest common divisor using Euclidean Algorithm
[Link](https://www.freecodecamp.org/news/euclidian-gcd-algorithm-greatest-common-divisor/)
|
| [AVLTree](src/algorithmsinanutshell/AVLTree.kt)
Kotlin • algorithmsinanutshell | Always a balanced tree https://www.youtube.com/watch?v=jDM6_TnYIqE
To delete a non-leaf/non-root node, remove it and find the right most descendant and put it there. The child of right most descendant will replace the old position of rightmost descendant
Since there are fixed number of rotation, it can be considered as O(1)
Other variations of tree are
* n-way tree like B-trees
* red-black tree with more relaxed rotation rules and enforces height of one branch isn't greater than 2x other branch
|
| [BucketSort](src/algorithmdesignmanualbook/sorting/BucketSort.kt)
Kotlin • sorting | Maintains bucket of 0..9 or a-z The number of iterations requires depends on number of characters in longest element (length wise)
[Algorithm](https://www.youtube.com/watch?v=JMlYkE8hGJM)
|
| [Permutation](src/algorithmdesignmanualbook/heuristics/backtrack/Permutation.kt)
Kotlin • backtrack | |
| [AllSubsets](src/algorithmdesignmanualbook/heuristics/backtrack/AllSubsets.kt)
Kotlin • backtrack | |
| [MinDifferenceBetweenSubsets](src/algorithmdesignmanualbook/dynamic/MinDifferenceBetweenSubsets.kt)
Kotlin • dynamic | |
| [EditDistance](src/algorithmdesignmanualbook/dynamic/EditDistance.kt)
Kotlin • dynamic | |
| [UnionFind](src/algorithmdesignmanualbook/graph/UnionFind.kt)
Kotlin • graph | Union-Find represent each subset as backward trees
! 0 ! 1 ! 2 !
! 1 ! 2 ! 0 !
[Video1](https://www.youtube.com/watch?v=ayW5B2W9hfo) - [Video2](https://www.youtube.com/watch?v=eTaWFhPXPz4) - [Solution](https://www.geeksforgeeks.org/union-find/)
|
| [PrimMinSpanningTree](src/algorithmdesignmanualbook/graph/PrimMinSpanningTree.kt)
Kotlin • graph | Solution: https://www.programiz.com/dsa/prim-algorithm
Given vertices with weighted edges, from start vertex, chose the edge with min edge such that it doesnt form cycle.
|
| [SimpleGraph](src/algorithmdesignmanualbook/graph/SimpleGraph.kt)
Kotlin • graph | |
| [Graph](src/algorithmdesignmanualbook/graph/Graph.kt)
Kotlin • graph | |
| [SmallestMissingNumber](src/algorithmdesignmanualbook/searching/SmallestMissingNumber.kt)
Kotlin • searching | [4-34] Suppose that you are given a sorted sequence of distinct integers {a1, a2, . . . , an}, drawn from 1 to m where n < m. Give an O(lg n) algorithm to find an integer ≤ m that is not present in a. For full credit, find the smallest such integer.
Solution: Binary search into the array. Since its sorted and starts from index 1, every element at index i should have element i.
|
| [MagicIndexSearch](src/algorithmdesignmanualbook/searching/MagicIndexSearch.kt)
Kotlin • searching | [4-33] Algorithm to determine whether there exists an i index such as ai = i given array of {a1, a2, a3 ... an} Sorted and distinct case: |
| [ColorSortLinearTime](src/algorithmdesignmanualbook/sorting/ColorSortLinearTime.kt)
Kotlin • sorting | Suppose an array A consists of n elements, each of which is red, white, or blue. We seek to sort the elements so that all the reds come before all the whites, which come before all the blues The only operation permitted on the keys are: examine and swap. |
| [KSum](src/algorithmdesignmanualbook/sorting/KSum.kt)
Kotlin • sorting | Given a set S of n integers and an integer T, give an algorithm to test whether k of the integers in S add up to T.
[Another way](https://www.geeksforgeeks.org/find-the-k-th-permutation-sequence-of-first-n-natural-numbers/)
### IDEA:
For target=21, k=3 i.e. 21/3 and array:

! 5 ! 6 ! 8 ! 10 ! 12 !
<------- 21/3 ------>
^ <--- 16/2 --->
^ <--- 10/1 --->
|
| [KSortedListMerge](src/algorithmdesignmanualbook/sorting/KSortedListMerge.kt)
Kotlin • sorting | Give an O(n log k)-time algorithm that merges k sorted lists with a total of n elements into one sorted list. (Hint: use a heap to speed up the elementary O(kn)-time algorithm). |
| [TwoPairSum](src/algorithmdesignmanualbook/sorting/TwoPairSum.kt)
Kotlin • sorting | O(nlogn) algorithm for finding whether there exists a pair of elements, one from S1 and one from S2, that add up to x |
| [ColorSort](src/algorithmdesignmanualbook/sorting/ColorSort.kt)
Kotlin • sorting | Assume that we are given n pairs of items as input, where the first item is a number and the second item is one of three colors (red, blue, or yellow). Further assume that the items are sorted by number. Give an O(n) algorithm to sort the items by color (all reds before all blues before all yellows) such that the numbers for identical colors stay sorted.
Solution: Maintain 3 queue for each color. At last, dequeue red, blue and then yellow
|
| [DynamicGrowShrinkArray](src/algorithmdesignmanualbook/datastructures/DynamicGrowShrinkArray.java)
Java • datastructures | |
| [CutoutsToGenerateString](src/algorithmdesignmanualbook/datastructures/CutoutsToGenerateString.kt)
Kotlin • datastructures | You are given a search string and a magazine. You seek to generate all the characters in search string by cutting them out from the magazine. Give an algorithm to efficiently determine whether the magazine contains all the letters in the search string
Notes:
* Cases matters
* Whitespace doesn't matter
|
| [LargestOccuringOrderedPair](src/algorithmdesignmanualbook/datastructures/LargestOccuringOrderedPair.kt)
Kotlin • datastructures | |
| [Node](src/algorithmdesignmanualbook/datastructures/Node.kt)
Kotlin • datastructures | |
| [IdenticalBinaryTree](src/algorithmdesignmanualbook/datastructures/IdenticalBinaryTree.kt)
Kotlin • datastructures | Given two binary tree, find if they are identical i.e. same value at the same position & same structure |
| [SmallestNumberInRange](src/algorithmdesignmanualbook/datastructures/SmallestNumberInRange.kt)
Kotlin • datastructures | Suppose that we are given a sequence of n values x1, x2, ..., xn and seek to quickly answer repeated queries of the form: given i and j, find the smallest value in xi, . . . , xj.
Given arrays of integer [values] of size n, convert it into matrix M of nxn such that M[i][j + 1] <= M[i][j] and anything before M[i][i] is null. M[i][i] holds the ith index item of [values]
|
| [NoInitializationArray](src/algorithmdesignmanualbook/datastructures/NoInitializationArray.kt)
Kotlin • datastructures | Design a data structure that allows one to search, insert, and delete an integer X in O(1) time (i.e. , constant time, independent of the total number of integers stored). Assume that 1 ≤ X ≤ n and that there are m + n units of space available, where m is the maximum number of integers that can be in the table at any one time. (Hint: use two arrays A[1..n] and B[1..m].) You are not allowed to initialize either A or B, as that would take O(m) or O(n) operations. This means the arrays are full of random garbage to begin with, so you must be very careful.
[Solution link](https://research.swtch.com/sparse):
Two arrays both of them with garbage value
* dense: contains actual elements in order of insertion
* sparse: uses *value* of [dense] as index and stores the *index* at which the value is located
So the search value v is legit iff index v of sparse array points to dense's index whose value is also v
|
| [MatrixMultiplication](src/algorithmdesignmanualbook/datastructures/MatrixMultiplication.kt)
Kotlin • datastructures | |
| [O1DataStructure](src/algorithmdesignmanualbook/datastructures/O1DataStructure.kt)
Kotlin • datastructures | Construct a DS with search, remove and add operations of O(1) in worst case The elements are drawn from the finite set and initialization can take place at O(n) |
| [MultiplicativeArray](src/algorithmdesignmanualbook/datastructures/MultiplicativeArray.kt)
Kotlin • datastructures | You have an unordered array X of n integers. Find the array M containing n elements where Mi is the product of all integers in X except for Xi. You may not use division. |
| [MiddleNodeOfLinkedList](src/algorithmdesignmanualbook/datastructures/MiddleNodeOfLinkedList.kt)
Kotlin • datastructures | Given a singly-linked list, find its middle node.
Solution: Fast pointer-slow pointer approach Use two pointer, one traverses one step ahead and another by 2 steps. When the fast pointer reaches the end, the slow pointer is at middle.
|
| [BinarySearchTree](src/algorithmdesignmanualbook/datastructures/BinarySearchTree.kt)
Kotlin • datastructures | |
| [ReverseSentence](src/algorithmdesignmanualbook/datastructures/ReverseSentence.kt)
Kotlin • datastructures | Reverse the words in a sentence—i.e., “My name is Chris” becomes “Chris is name My.” |
| [StringPatternMatching](src/algorithmdesignmanualbook/datastructures/StringPatternMatching.kt)
Kotlin • datastructures | Find substring match
O(ab) where a = len of pattern and b = len of string
|
| [BalancedParentheses](src/algorithmdesignmanualbook/datastructures/BalancedParentheses.kt)
Kotlin • datastructures | Check if a string contains properly nested and balanced parentheses, and false if otherwise. |
| [FlattenBSTIntoLinkedList](src/algorithmdesignmanualbook/datastructures/FlattenBSTIntoLinkedList.kt)
Kotlin • datastructures | |
| [ReverseLinkedList](src/algorithmdesignmanualbook/datastructures/ReverseLinkedList.kt)
Kotlin • datastructures | [link here](https://leetcode.com/problems/reverse-linked-list) |
| [HeapSort](src/algorithmdesignmanualbook/sorting/HeapSort.kt)
Kotlin • sorting | |
| [MergeSort](src/algorithmdesignmanualbook/sorting/MergeSort.kt)
Kotlin • sorting | |
| [InsertionSort](src/algorithmdesignmanualbook/sorting/InsertionSort.kt)
Kotlin • sorting | How does insertion sort work?
* Loop through elements
* At each element, compare it with element before it
* If smaller, swap places
* Repeat
|
| [SelectionSort](src/algorithmdesignmanualbook/sorting/SelectionSort.kt)
Kotlin • sorting | Identify the smallest element from unsorted portion and put it at the end of the sorted portion |
| [QuickSort](src/algorithmdesignmanualbook/sorting/QuickSort.kt)
Kotlin • sorting | |
| [PartialSumUsingFenwickTree](src/algorithmdesignmanualbook/partialsum/PartialSumUsingFenwickTree.kt)
Kotlin • partialsum | Let A be an array of n real numbers. Design an algorithm to perform any sequence of the following operations: • Add(i,y) – Add the value y to the ith number. • Partial-sum(i) – Return the sum of the first i numbers Each operation must take O(logn).
Fenwick Tree or Binary Indexed Tree is a tree containing n+1 nodes. Each node's parent is right most 1 flipped i.e
* 8 -> 1000 so parent is 0000 (0)
* 7 -> 0111 so parent is 0110 (6)
* 10 -> 1010 so parent is 1000 (8)
* 5 -> 0101 so parent is 0100 (4) Sum can be obtained by (0..5) -> tree[6] + tree[4] + tree[0] i.e index+1 and then go upwards to parents
To get the parent:
* 2's complement (Flip all bits and add 1)
* AND it with original number
* Subtract it from original number
7 (111) ---(step 1)---> 000+1=001 ---(AND 111)-->001 --(Subtract from 111)--->110
|
| [PartialSumUsingCumulativeSum](src/algorithmdesignmanualbook/partialsum/PartialSumUsingCumulativeSum.kt)
Kotlin • partialsum | Let A[1..n] be an array of real numbers. Design an algorithm to perform any sequence of the following operations: • Add(i,y) – Add the value y to the ith number. • Partial-sum(i) – Return the sum of the first i numbers |
| [RecursiveMultiply](src/dynamic/RecursiveMultiply.java)
Java • dynamic | Multiply without using *. |
| [PermutationWithDuplicates](src/dynamic/PermutationWithDuplicates.java)
Java • dynamic | [Video](https://www.youtube.com/watch?v=JF4QrlUJItk) |
| [Coins](src/dynamic/Coins.java)
Java • dynamic | |
| [EightQueens](src/dynamic/EightQueens.java)
Java • dynamic | |
| [PaintFill](src/dynamic/PaintFill.java)
Java • dynamic | Implement the"paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color |
| [Parens](src/dynamic/Parens.java)
Java • dynamic | Implement an algorithm to print all valid (i.e., properly opened and closed) combinations of n pairs of parentheses |
| [PermutationWithoutDuplicates](src/dynamic/PermutationWithoutDuplicates.java)
Java • dynamic | |
| [BooleanEvaluation](src/dynamic/BooleanEvaluation.java)
Java • dynamic | |
| [TowerOfHanoi](src/dynamic/TowerOfHanoi.java)
Java • dynamic | |
| [SortedMatrixSearch](src/sortingandsearch/SortedMatrixSearch.java)
Java • sortingandsearch | |
| [RankFromStream](src/sortingandsearch/RankFromStream.java)
Java • sortingandsearch | Imagine you are reading in a stream of integers. Periodically, you wish to be able to look up the rank of a number x (the number of values less than or equal to x). Implement the data structures and algorithms to support these operations. That is, implement the method track(int x), which is called when each number is generated, and the method getRankOfNumber(int x), which returns the number of values less than or equal to x (not including x itself). |
| [SortedSearchNoSize](src/sortingandsearch/SortedSearchNoSize.java)
Java • sortingandsearch | You are given an array-like data structure Listy which lacks a size method. It does, however, have an elementAt(i) method that returns the element at index i in 0(1) time. If i is beyond the bounds of the data structure, it returns -1. (For this reason, the data structure only supports positive integers.) Given a Listy which contains sorted, positive integers, fnd the index at which an element x occurs. If x occurs multiple times, you may return any index. |
| [PeaksAndValley](src/sortingandsearch/PeaksAndValley.java)
Java • sortingandsearch | |
| [GroupAnagrams](src/sortingandsearch/GroupAnagrams.java)
Java • sortingandsearch | Write a method to sort an array ot strings so that all tne anagrams are next to each other. |
| [SortedMerge](src/sortingandsearch/SortedMerge.java)
Java • sortingandsearch | You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order. |
| [SparseSearch](src/sortingandsearch/SparseSearch.java)
Java • sortingandsearch | Given a sorted array of strings that is interspersed with empty strings, write a method to fnd the location of a given string. |
| [Shuffle](src/hard/Shuffle.java)
Java • hard | |
| [AddWithoutPlus](src/hard/AddWithoutPlus.java)
Java • hard | |
| [RandomSet](src/hard/RandomSet.java)
Java • hard | |
| [PermutationCount](src/bigo/PermutationCount.java)
Java • bigo | |
| [PowerOf2](src/bigo/PowerOf2.java)
Java • bigo | |
| [PairwiseSwap](src/bits/PairwiseSwap.java)
Java • bits | Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit O and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on) |
| [Conversion](src/bits/Conversion.java)
Java • bits | Number of bits you have to flip to convert bits A to bits B |
| [BinaryToString](src/bits/BinaryToString.java)
Java • bits | Given a real number between 0 & 1 (eg. 0.72) that is passed in as double, print the binary representation. If # cannot be expressed in binary with at most 32 bits, then throw ERROR. |
| [Insertion](src/bits/Insertion.java)
Java • bits | |
| [FlipBitToWin](src/bits/FlipBitToWin.java)
Java • bits | Find the largest sequence of 1 that can be obtained by flipping a 0 to 1. |
| [BitUtils](src/bits/commons/BitUtils.java)
Java • commons | |
| [FizzBuzz](src/threads/FizzBuzz.java)
Java • threads | |
| [PickRandomNode](src/graphs/PickRandomNode.java)
Java • graphs | |
| [CheckBST](src/graphs/CheckBST.java)
Java • graphs | left <= current < right |
| [ListOfDepth](src/graphs/ListOfDepth.java)
Java • graphs | Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists). |
| [CheckBalanced](src/graphs/CheckBalanced.java)
Java • graphs | |
| [PathWithSum](src/graphs/PathWithSum.java)
Java • graphs | |
| [BuildOrder](src/graphs/BuildOrder.java)
Java • graphs | |
| [CheckIfSubTree](src/graphs/CheckIfSubTree.java)
Java • graphs | Check if a tree is a subtree of another |
| [MinimalTree](src/graphs/MinimalTree.java)
Java • graphs | Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height. |
| [RoutesBetweenNodes](src/graphs/RoutesBetweenNodes.java)
Java • graphs | |
| [FirstCommonAncestor](src/graphs/FirstCommonAncestor.java)
Java • graphs | |
| [Tree](src/graphs/commons/Tree.java)
Java • commons | |
| [Node](src/graphs/commons/Node.java)
Java • commons | |
| [BidirectionalTree](src/graphs/commons/BidirectionalTree.java)
Java • commons | |
| [Graph](src/graphs/commons/Graph.java)
Java • commons | |
| [UniqueCharacters](src/arraysandstrings/UniqueCharacters.java)
Java • arraysandstrings | |
| [IsOneStringPermutationOfOther](src/arraysandstrings/IsOneStringPermutationOfOther.java)
Java • arraysandstrings | |
| [StringCompression](src/arraysandstrings/StringCompression.kt)
Kotlin • arraysandstrings | |
| [IsPermutationOfStringAPalindrome](src/arraysandstrings/IsPermutationOfStringAPalindrome.kt)
Kotlin • arraysandstrings | |
| [OneAway](src/arraysandstrings/OneAway.kt)
Kotlin • arraysandstrings | |
| [StringRotation](src/arraysandstrings/StringRotation.kt)
Kotlin • arraysandstrings | |
| [MatrixRotation](src/arraysandstrings/MatrixRotation.kt)
Kotlin • arraysandstrings | |
| [URLify](src/arraysandstrings/URLify.kt)
Kotlin • arraysandstrings | |
| [SumLists](src/linkedlists/SumLists.kt)
Kotlin • linkedlists | |
| [LinkedListDuplicate](src/linkedlists/LinkedListDuplicate.kt)
Kotlin • linkedlists | |
| [LinkedList](src/linkedlists/LinkedList.kt)
Kotlin • linkedlists | |
| [FormatPhoneNumber](src/questions/FormatPhoneNumber.kt)
Kotlin • questions | Given a phone number should format in the form of abc-def-ijk. Last two part can be of 2 digits |
| [SearchContact](src/questions/SearchContact.kt)
Kotlin • questions | |
| [baby_names](python/hard/baby_names.py)
Python • hard | |
| [letters_and_numbers](python/hard/letters_and_numbers.py)
Python • hard | Given an array filled with letters and numbers, fnd the longest subarray with an equal number of letters and numbers
:param string: string
:return: subarray
|
| [count_of_2s](python/hard/count_of_2s.py)
Python • hard | Find the number of 2s in between 0 and n
:param number: the max value (inclusive)
:return: Number of 2s
|
| [langton_ant](python/moderate/langton_ant.py)
Python • moderate | An ant is sitting on an infinite grid of white and black squares. It initially faces right. At each step, it does the following: (1) At a white square, flip the color of the square, turn 90 degrees right (clockwise), and move forward one unit. (2) At a black square, flip the color of the square, turn 90 degrees left (counter-clockwise), and move forward one unit. Write a program to simulate the first K moves that the ant makes and print the final board as a grid. |
| [calculator](python/moderate/calculator.py)
Python • moderate | |
| [pairs_with_sum](python/moderate/pairs_with_sum.py)
Python • moderate | |
| [pond_sizes](python/moderate/pond_sizes.py)
Python • moderate | You have an integer matrix representing a plot of land, where the value at that location represents the height above sea level. A value of zero indicates water. A pond is a region of water connected vertically, horizontally, or diagonally. The size of the pond is the total number of connected water cells. Write a method to compute the sizes of all ponds in the matrix |
| [swap_sum](python/moderate/swap_sum.py)
Python • moderate | |
| [pattern_matching](python/moderate/pattern_matching.py)
Python • moderate | You are given two strings, pattern and value. The pattern string consists of just the letters a and b, describing a pattern within a string. For example, the string catcatgocatgo matches the pattern aabab (where cat is a and go is b). It also matches patterns like a, ab, and b. Write a method to determine if value matches pattern. |
| [continuous_sequence](python/moderate/continuous_sequence.py)
Python • moderate | |
| [master_mind](python/moderate/master_mind.py)
Python • moderate | |
| [sub_sort](python/moderate/sub_sort.py)
Python • moderate | |
| [bisect_squares](python/moderate/bisect_squares.py)
Python • moderate | |
| [diving_board](python/moderate/diving_board.py)
Python • moderate | Arranging k planks end-to-end means that arranging (k short, 0 long), (k-1 short, 1 long), (k-2 short, 2 long)...
:param k: the number of planks
:return: the all possible length of arrangements
|
| [xml_encoding](python/moderate/xml_encoding.py)
Python • moderate | |
| [count_pairs_with_difference](python/moderate/count_pairs_with_difference.py)
Python • moderate | |
| [operation](python/moderate/operation.py)
Python • moderate | |
| [living_people](python/moderate/living_people.py)
Python • moderate | |
| [factorial_zeros](python/moderate/factorial_zeros.py)
Python • moderate | |
| [smallest_difference](python/moderate/smallest_difference.py)
Python • moderate | |
| [english_int](python/moderate/english_int.py)
Python • moderate | |
| [tic_tac](python/moderate/tic_tac.py)
Python • moderate | |
| [intersection](python/moderate/intersection.py)
Python • moderate | |
| [needle](python/needle.py)
Python • python | |
| [reverseint](python/reverseint.py)
Python • python | |
| [three_sums](python/three_sums.py)
Python • python | |
| [multiply](python/multiply.py)
Python • python | |
| [paritysort](python/paritysort.py)
Python • python | |
| [remove_element](python/remove_element.py)
Python • python | |
| [longestsubstr](python/longestsubstr.py)
Python • python | |
| [addTwoNumbers](python/addTwoNumbers.py)
Python • python | |
| [sumEvenAfterQueries](python/sumEvenAfterQueries.py)
Python • python | |
| [valid_paranthesis](python/valid_paranthesis.py)
Python • python | |
| [stack_of_plates](python/stacksqueues/stack_of_plates.py)
Python • stacksqueues | |
| [stack](python/stacksqueues/stack.py)
Python • stacksqueues | |
| [animal_shelter](python/stacksqueues/animal_shelter.py)
Python • stacksqueues | |
| [queueviastacks](python/stacksqueues/queueviastacks.py)
Python • stacksqueues | |
| [stack_min](python/stacksqueues/stack_min.py)
Python • stacksqueues | |
| [sort_stack](python/stacksqueues/sort_stack.py)
Python • stacksqueues | |
| [string_compression](python/codinginterview/string_compression.py)
Python • codinginterview | |
| [delete_middle](python/codinginterview/delete_middle.py)
Python • codinginterview | Delete kth node from linked list
Parameters: linked_ (LinkedList): a Linked List k (int): the kth position
|
| [quick_sort](python/codinginterview/quick_sort.py)
Python • codinginterview | |
| [merge_sort](python/codinginterview/merge_sort.py)
Python • codinginterview | |
| [zero_matrix](python/codinginterview/zero_matrix.py)
Python • codinginterview | Make INPLACE row and column of a matrix 0 iff that row contains a 0 |
| [string_rotation](python/codinginterview/string_rotation.py)
Python • codinginterview | Check if one string is formed by rotating the other string eg: abcd, dabc, cdab, bcda |
| [delete_duplicates](python/codinginterview/delete_duplicates.py)
Python • codinginterview | Delete duplicate node from a Linked List
Parameters: linked_list: The list to be deleted from
|
| [kth_to_last](python/codinginterview/kth_to_last.py)
Python • codinginterview | Get all nodes from kth position to the end |
| [matrix_rotation](python/codinginterview/matrix_rotation.py)
Python • codinginterview | |
| [linked_list](python/codinginterview/shared/linked_list.py)
Python • shared | |
| [base_linked_list](python/codinginterview/shared/base_linked_list.py)
Python • shared | |
| [reversed_linked_list](python/codinginterview/shared/reversed_linked_list.py)
Python • shared | |
| [circular_linked_list](python/codinginterview/shared/circular_linked_list.py)
Python • shared | |
| [node](python/codinginterview/shared/node.py)
Python • shared | |

___
This README was auto-generated during pre-commit.

##### IntelliJ Live Template
```
import _utils.UseCommentAsDocumentation

/**
* $END$
* [Source](https://leetcode.com/problems/$camelCase$/)
*/
@UseCommentAsDocumentation
private fun solution() {
}

fun main() {
}
```
where `camelCase`=`lowercaseAndDash(fileName())`