Below you will find pages that utilize the taxonomy term “PROBLEM”
Posts
Check Inclusion
PROBLEM Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, return true if one of s1’s permutations is the substring of s2.
Example1 *Input*: s1 = "ab", s2 = "eidbaooo" *Output*: true Explanation: s2 contains one permutation of s1 ("ba"). Example2 =Input=: s1 = "ab", s2 = "eidboaoo" =Output=: false SOLVING Steps Create two vectors of size 26 filled by some 0 for the two string Fill the first vector with the string s1: For each char: Increase by one at position char - 'a' (transform a-z into 0-26) Create index i and j to 0 Use j to parcor string s2 and increase by one the second vector at position s2[j] If j-i equal length of string s1 that means second vector has enough information to compare two vector for permutation If j-i inferior at length of string s1 that means second vector doesn’t has enough information to compare two vector for permutation, so only increase j Otherwise increase i and j and decrease s2[i] because not in the scoop of search anymore If previous compare didn’t work return false Code class Solution { private: bool areVectorsEqual(vector<int> a, vector<int> b) { for (int i = 0; i < 26; i++) { if (a[i] !
read morePosts
Climbing Stairs
PROBLEM 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?
Example1 *Input*: n = 2 *Output*: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example2 *Input*: n = 3 *Output*: 3 Explanation: There are three ways to climb to the top.
read morePosts
Defuse The Bomb
PROBLEM You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k.
To decrypt the code, you must replace every number. All the numbers are replaced simultaneously.
If k > 0, replace the ith number with the sum of the next k numbers. If k < 0, replace the ith number with the sum of the previous k numbers.
read morePosts
Find All Anagrams in a String
PROBLEM 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.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1 *Input*: s = "cbaebabacd", p = "abc" *Output*: [0,6] *Explanation*: The substring with start index = 0 is "cba", which is an anagram of "abc".
read morePosts
Group Anagrams
PROBLEM Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example1 *Input*: strs = ["eat","tea","tan","ate","nat","bat"] *Output*: [["bat"],["nat","tan"],["ate","eat","tea"]] Example2 *Input*: strs = [""] *Output*: [ [""] ] Example3 *Input*: strs = ["a"] *Output*: [ ["a"] ] SOLVING We’ll use Hash and Array to solve this problem
read morePosts
House Robber
PROBLEM You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
read morePosts
Interval List Intersections
PROBLEM You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
A closed interval [a, b] (with a<=b) denotes the set of real numbers x with a<=x<=b.
The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval.
read morePosts
Is Power Of Two
PROBLEM Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n = 2x.=
Example1 *Input*: n = 1 *Output*: true Explanation: 20 = 1 Example2 *Input*: n = 16 *Output*: true Explanation: 24 = 16 Example3 *Input*: n = 3 *Output*: false SOLVING we’ll use Bit manipulation method.
read morePosts
Letter Case Permutation
PROBLEM Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create. Return the output in any order.
Example1 *Input*: s = "a1b2" *Output*: ["a1b2","a1B2","A1b2","A1B2"] Example2 *Input*: s = "3z4" *Output*: ["3z4","3Z4"] Constraints s consits of lowercase English letters, uppercase English letters and digits SOLVING we’ll use Backtracking method.
Steps If the index equal to size push to the result the string Call once the method with the exact same string and just the index + 1 If the current element is an alpha change uppercase <–> lowercase and call a second time the method Return the result Code class Solution { public: vector<string> letterCasePermutation(string s) { vector<string> result; backtrack(s, 0, s.
read morePosts
Longest Substring Without Repeating Characters
PROBLEM Given a string s, find the length of the longest substring without repeating characters.
Example1 *Input*: s = "abcabcbb" *Output*: 3 Explanation: The answer is "abc", with the length of 3. Example2 *Input*: s = "bbbbb" *Output*: 1 Explanation: The answer is "b", with the length of 1. Example3 *Input*: s = "pwwkew" *Output*: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
read morePosts
Matrix Distance Nearest 0
PROBLEM Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example1 *Input*: mat = [[0,0,0],[0,1,0],[0,0,0]] *Output*: [[0,0,0],[0,1,0],[0,0,0]] Example2 *Input*: mat = [[0,0,0],[0,1,0],[1,1,1]] *Output*: [[0,0,0],[0,1,0],[1,2,1]] SOLVING we’ll use Breadth-first Search method
Steps Create matrix result with the same size filled by 0 Create a queue Parcor the list if there is a 1 next to a 0 : Add in result 1 at it’s position (because it’s at one cell from a zero) And push to the queue it’s position While queue not empty: Pop the queu to get the current value Check the neighboors (up, down, right, left) If it’s equal to 1 and equal to 0 in result (That means we didn’t see this cell before): Push to the queue it’s position Add in result the parent value in result + 1 Return result Code class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>> &mat) { m = mat.
read morePosts
Max Area Of Island Array
PROBLEM 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.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of an island in grid. If there is no island, return 0.
read morePosts
Merge Two Binary Trees
PROBLEM You are given two binary trees root1 and root2.
Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
read morePosts
Minimum Path Sum
PROBLEM Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example *Input*: grid = [[1,3,1],[1,5,1],[4,2,1]] *Output*: 7 Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum. Constraints m==grid.length n==grid[i].length 1<=m, n<=200 0<=grid[i][j]<=100 SOLUTION We’ll use Dynamic Programming method.
read morePosts
Minimum Penalty for a Shop
PROBLEM You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y':
if the ith character is 'Y' , it means that customers come at the ith hour whereas 'N' indicates that no customers come at the ith hour. If the shop closes at the jth hour (0<=j<=n), the penalty is calculated as follows:
For every hour when the shop is open and no customers come, the penalty increases by 1.
read morePosts
Minimum Time To Type Using Special Typewritter
PROBLEM There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.
Each second, you may perform one of the following operations:
Move the Pointer one character counterclockwise or clockwise Type the character the pointer is currently only Given a string word, return the minimum number of seconds to type out the characters in word.
read morePosts
Move Zeroes
PROBLEM Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example1 *Input*: nums = [0,1,0,3,12] *Output*: [1,3,12,0,0] Example2 *Input*: nums = [0] *Output*: [0] Constraints 1<=nums.length<=104 -231<=nums[i]<=231-1 Follow up: Could you minimize the total number of operations done?
SOLVING We’ll use the Two Pointers method
read morePosts
Palindrome Number
PROBLEM Given an integer x, return true if x is a palindrome, and false otherwise.
Example1 *Input*: x = 121 *Output*: true *Explanation*: 121 reads as 121 from left to right and from right to left. Example2 *Input*: x = -121 *Output*: false *Explanation*: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example3 *Input*: x = 10 *Output*: false *Explanation*: Reads 01 from right to left.
read morePosts
Permutation
PROBLEM Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example1 *Input*: nums = [1,2,3] *Output*: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example2 *Input*: nums = [0,1] *Output*: [[0,1],[1,0]] Example3 *Input*: nums = [1] *Output*: [ [1] ] Constraints 1<=nums.length<=6 -10<=nums[i]<=10 All the integers of nums are unique. SOLVING we’ll use Backtracking method
Steps Backtracking method: push in result and return if current index equal size for each index between current index and size: swap in nums the element at current index and index from for loop call in recursive the backtrack method with as parameter current index + 1 re swap in nums the element at current index and index from for loop to reset the change return result Code class Solution { public: vector<vector<int>> permute(vector<int> &nums) { backtrack(nums, 0, nums.
read morePosts
Populating Next Right Pointers In Each Node
PROBLEM You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
read morePosts
Problem Solving
Problem solving is the process of identifying and then implementing a solution to a problem.
read morePosts
Product of Array Except Self
PROBLEM Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
Example 1 **Input**: nums = [1,2,3,4] **Output**: [24,12,8,6] Example 2 **Input**: nums = [-1,1,0,-3,3] **Output**: [0,0,9,0,0] SOLVING We are going to make to iteration.
read morePosts
Remove Duplicates from Sorted List II
PROBLEM Given the head of a sorted Linked List, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Example1 *Input*: head = [1,2,3,3,4,4,5] *Output*: [1,2,5] SOLVING We’ll use Two Pointers method to solve this problem
Steps Create a Node dummy with val (0 for this example) pointing to head Create a Node prev equal to dummy Parcor the Linked List: If the current value and the next are the same: Loop until the node value is different prev->next equal to this node Otherwise move prev and head of a node Return the next of dummy (previously the pointer to head) Code class Solution { public: ListNode *deleteDuplicates(ListNode *head) { ListNode *dummy = new ListNode(0, head); ListNode *prev = dummy; while (head) { if (head->next && head->val == head->next->val) { while (head->next && head->val == head->next->val) head = head->next; prev->next = head->next; } else prev = prev->next; head = head->next; } return dummy->next; } };
read morePosts
Reverse Bits
PROBLEM Reverse bits of a given 32 bits unsigned integer.
SOLVING We’ll use Bit Manipulation method
Steps Create a uint32_t result we’ll return as the answer Repeat 32 time or the longer of your bit result equal to result or (| or bit operation) on the result of n and (& and bit operation) 1 to get the first bit Example Example with 6bit (32 is tooooo long) 011101
=n= [011101] & 1 == 1 =result= [000000] << 1 =n= [001110] & 1 == 0 =result= [000001] << 0 =n= [000111] & 1 == 1 =result= [000010] << 1 =n= [000011] & 1 == 1 =result= [000101] << 1 =n= [000001] & 1 == 1 =result= [001011] << 1 =n= [000000] & 1 == 0 =result= [010111] << 0 =result= [101110] Code class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t result; for (int i = 0; i < 32; i++) { result = (result << 1) | (n & 1); n >>= 1; } return result; } };
read morePosts
Reverse Linked List
PROBLEM Given the head of a singly Linked List, reverse the list, and return the reversed list.
Example1 *Input*: head = [1,2,3,4,5] *Output*: [5,4,3,2,1] Example2 *Input*: head = [1,2] *Output*: [2,1] Example3 *Input*: head = [] *Output*: [] SOLVING Steps Create prevNode and nextNode to solve this problem nextNode equal head next N head next equal prevNode H prevNode equal head P head equal nextNode return prevNode Example1 P H N ↓ ↓ ↓ NULL [1 -> 2 -> 3 -> 4 -> 5 -> NULL] head next equal prevNode head equal next P H N ↓ ↓ ↓ [NULL <- 1 2 -> 3 -> 4 -> 5 -> NULL] head next equal prevNode head equal next P H N ↓ ↓ ↓ [NULL <- 1 <- 2 3 -> 4 -> 5 -> NULL] head next equal prevNode head equal next P H N ↓ ↓ ↓ [NULL <- 1 <- 2 <- 3 4 -> 5 -> NULL] head next equal prevNode head equal next P H N ↓ ↓ ↓ [NULL <- 1 <- 2 <- 3 <- 4 5 -> NULL] head next equal prevNode head equal next P H N ↓ ↓ ↓ [NULL <- 1 <- 2 <- 3 <- 4 <- 5] NULL] Return prevNode Code class Solution { public: ListNode *reverseList(ListNode *head) { ListNode *nextNode = nullptr; ListNode *prevNode = nullptr; while (head) { nextNode = head->next; head->next = prevNode; prevNode = head; head = nextNode; } return prevNode; } };
read morePosts
Reverse Words
PROBLEM Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example1 *Input*: s = "Let's take LeetCode contest" *Output*: "s'teL ekat edoCteeL tsetnoc" Example2 *Input*: s = "God Ding" *Output*: "diG gniD" Constraints 1<=s.length<=5*104 s contains printable ASCII characters. s does not contain any leading or trailing spaces. There is at least one word in s. All the words in s are separated by a single space.
read morePosts
Rotate Array
PROBLEM Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
Example 1 *Input*: nums = [1,2,3,4,5,6,7], k = 3 *Output*: [5,6,7,1,2,3,4] *Explanation*: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2 *Input*: nums = [-1,-100,3,99], k = 2 *Output*: [3,99,-1,-100] *Explanation*: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] SOLVING We’ll use the Two Pointers method
read morePosts
Rotting Oranges
PROBLEM You are given a m x n grid where each cell can have one of three values:
0 representing an empty cell, 1 representing a fresh orange, or 2 representing a rotten orange. Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.
read morePosts
Search a 2D Matrix
PROBLEM You are given an m x n integer matrix matrix with the following two properties:
Each row is sorted in non-decreasing order. The first integer of each row is greater than the last integer of the previous row. Given an integer target, return true if target is in matrix or false otherwise.
You must write a solution in O(log(m * n)) time complexity.
Example1 *Input*: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 *Output*: true Example2 *Input*: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 *Output*: false SOLVING we’ll use Binary Search exact value to solve this problem
read morePosts
Search Insert
PROBLEM In an sorted array [1, 3, 5, 6, 8], you want to know the index to insert your target, 5 In an sorted array [1, 3, 5, 6, 8], you want to know the index to insert your target, 2 SOLVING Use of Binary Search method.
This code will return the index 2, where the target already is This code will return the index 1 where the target should be Steps Place Left Pointer at 0 and Right Pointer to the last element Until Left Element is inferior to Right Element: Get the element between left and right Middle Index=(Left Index - RIght Index) / 2 If Middle Element equal the target, return If it’s inferior, Left Pointer becomes the Middle Pointer Otherwise it’s superior, and so Right Pointer become the Middle Pointer If the loop is finished return the Left Pointer Code #include <iostream> #include <vector> int searchInsert(std::vector<int> &nums, int target) { int l = 0; int r = nums.
read morePosts
Square Of A Sorted Array
PROBLEM Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order
Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?
Example1 *Input*: nums = [-4,-1,0,3,10] *Output*: [0,1,9,16,100] *Explanation*: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example 2 *Input*: nums = [-7,-3,2,3,11] *Output*: [4,9,9,49,121] SOLVING We will use Two Pointers technique.
read morePosts
SubRectangleQueries
PROBLEM Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:
updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2).
getValue(int row, int col) Returns the current value of the coordinate (row,col) from the rectangle.
You want to update element between row2 and row3 and between col3 and col6
read morePosts
Top K Frequent Elements
PROBLEM Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Example 1 *Input*: nums = [1,1,1,2,2,3], k = 2 *Output*: [1,2] Example 2 *Input*: nums = [1], k = 1 *Output*: [1] SOLVING We’ll use the Bucket Sort method.
Steps Create a Map to store the frequency of each letters, a Map buckets and the array for the result Iterate on the string use each letter as key for frequency and increase by one the value Fill the buckets by using the value of frequency as the key of buckets and add the key of frequency in the value of the bucket Iterate from the end of buckets: Iterate on each element in the bucket value: Add this element to result if result length is equal to k return result Example With the parameters nums = [1,1,1,2,2,3] and k = 2
read morePosts
Two Sum || Array Sorted
PROBLEM 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. Let these two numbers be numbers[index1] and numbers[index2] where 1<=index1<index2<=numbers.length.
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution.
read morePosts
Valid Parentheses
PROBLEM Given a string s containing just the characters '(' , ')' , '{' , '}' , '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Every close bracket has a corresponding open bracket of the same type. Example1 *Input*: s = "()" *Output*: true Example2 *Input*: s = "([]){}" *Output*: true Example3 *Input*: s = "(]" *Output*: false SOLVING Steps Create a Stack Browse the string: If characters is an open parentheses push to the stack If characters is an close parentheses If the top of the stack is the open equivalent pop the stack Otherwise return false, the string isn’t closing the last open parentheses Otherwise return false, the character isn’t an open or close parentheses return true if the stack is empty otherwise false because all parentheses aren’t closed Code class Solution { public: bool isValid(string s) { const string open = "({["; const string close = ")}]"; stack<char> parenthesesOpen; for (int i = 0; i < s.
read morePosts
Valid Phone Numbers
PROBLEM Given a text file file.txt that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone numbers.
You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)
You may also assume each line in the text file must not contain leading or trailing white spaces.
read more