My Leetcode Solutions
Hey Coders!
Greetings and welcome to my Leetcode Solutions vault! This corner of the web is fuelled directly from my Obsidian Vault and served up with the magic of Next.js.
Curious how I built this? Check how-i-built-this-websiteHow I Built This WebsiteThis website is powered by 2 Github Repository, namely, 1. davzoku/leetcode-obsidian-frontend : The Next.js frontend hosted in Netlify 1. davzoku/leetcode-obsidian-vault: The Obsidian Vault containing the Leetcode Solutions. In fact, the setup is forked from matthewwong525/linked-blog-starter and matthewwong525/linked-blog-starter-md. It is also well-explained in this video link. The Obsidian Git plugin is set up to push any changes in X minute intervals. This will trigger a Github Action w
What's the Plan?
Let's break it down – my mission here is to dive into LeetCode questions, get cozy with them, and understand the ninja moves to crack these coding conundrums.
- Daily Dive: I'm committing 30 minutes each day to tackle a question, usually the daily one.
- Expectations: Expect solutions, explanations, and the nitty-gritty of time and space complexities.
- Honesty Check: If I hit a roadblock within that timeframe, I'm not shy to peek at solutions on YouTube or Leetcode. Learning is the goal, right?
- Marathon Mentality: Remember, this is a marathon, not a sprint. Every day we pick up something new – that's the win.
Solved Problems
- 1-two-sum1 Two Sum - EasyProblem: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have *exactly* one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = \[2,7,11,15\], target = 9 Output: \[0,1\] Explanation: Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. Example 2: Input: nums = \[3,2,4\], target = 6 Output: \[1,2\] Example 3:
- 2-add-two-numbers2 Add Two Numbers - MediumProblem: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example 1: Input: l1 = \[2,4,3\], l2 = \[5,6,4\] Output: \[7,0,8\] Explanation: 342 + 465 = 807. Example 2: Input: l1 = \[0\], l2 = \[0\] Output: \[0\] Example 3:
- 6-zigzag-conversion6 Zigzag Conversion - MediumProblem: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s =
- 14-longest-common-prefix14 Longest Common Prefix - EasyProblem: 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 "". Example 1: Input: strs = \["flower","flow","flight"\] Output: "fl" Example 2: Input: strs = \["dog","racecar","car"\] Output: "" Explanation: There is no common prefix among the input strings. Constraints: * `1 str: for i in range(len(strs[0])): for j in range(1, len(strs)): if i == len(strs[j]) or s
- 20-valid-parentheses20 Valid Parentheses - EasyProblem: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 1. Open brackets must be closed in the correct order. 1. Every close bracket has a corresponding open bracket of the same type. Example 1: Input: s = "()" Output: true Example 2: Input: s = "()\[\]{}" Output: true Example 3: Input: s = "(\]" Output: false Constraints:
- 35-search-insert-position35 Search Insert Position - EasyProblem: 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. Example 1: Input: nums = \[1,3,5,6\], target = 5 Output: 2 Example 2: Input: nums = \[1,3,5,6\], target = 2 Output: 1 Example 3: Input: nums = \[1,3,5,6\], target = 7 Output: 4 Constraints: * `1 int: l, r = 0, len(nums) -1 wh
- 41-find-missing-positive41 First Missing Positive - HardProblem: Given an unsorted integer array nums, return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space. Example 1: Input: nums = \[1,2,0\] Output: 3 Explanation: The numbers in the range \[1,2\] are all in the array. Example 2: Input: nums = \[3,4,-1,1\] Output: 2 Explanation: 1 is in the array but 2 is missing. Example 3: Input: nums = \[7,8,9,11,12\] Output: 1 Explanation: The smallest positive integer 1 is mis
- 53-maximum-subarray53 Maximum Subarray - MediumProblem: Given an integer array nums, find the subarray with the largest sum, and return its sum. Example 1: Input: nums = \[-2,1,-3,4,-1,2,1,-5,4\] Output: 6 Explanation: The subarray \[4,-1,2,1\] has the largest sum 6. Example 2: Input: nums = \[1\] Output: 1 Explanation: The subarray \[1\] has the largest sum 1. Example 3: Input: nums = \[5,4,-1,7,8\] Output: 23 Explanation: The subarray \[5,4,-1,7,8\] has the largest sum 23. Constraints: * `1 int: max_so_far: overall maximum s
- 58-length-of-last-wordProblem: Given a string s consisting of words and spaces, return the length of the *last* word in the string. A word is a maximal substring consisting of non-space characters only. Example 1: Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5. Example 2: Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4. Example 3: Input: s = "luffy is still joyboy" Output: 6 Explanation: The last word is "joyboy" wi
- 66-plus-one66 Plus One - EasyProblem: 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. Example 1: Input: digits = \[1,2,3\] Output: \[1,2,4\] Explanation: The array represents the integer 123. Incrementing by one gives 123 + 1 = 1
- 69-sqrt-x69 Sqrt(x) - EasyProblem: Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well. You must not use any built-in exponent function or operator. * For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python. Example 1: Input: x = 4 Output: 2 Explanation: The square root of 4 is 2, so we return 2. Example 2: Input: x = 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we round it down to t
- 70-climbing-stairs70 Climbing Stairs - EasyProblem: 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? Example 1: Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 1. 2 steps Example 2: Input: n = 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 1. 1 step + 2 steps 1. 2 steps + 1 step Constraints: * 1 <= n <= 45 Problem Analysi
- 91-decode-ways91 Decode Ways - MediumProblem: A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: * "AAJF" with the grouping (1 1 10 6) * "KJF" with the grouping (11 10 6) Note that the grouping (1 11 06) is invalid because "06" cannot be mapped int
- 94-binary-tree-inorder-traversal94 Binary Tree Inorder Traversal - EasyProblem: Given the root of a binary tree, return the inorder traversal of its nodes' values. Example 1: Input: root = \[1,null,2,3\] Output: \[1,3,2\] Example 2: Input: root = \[\] Output: \[\] Example 3: Input: root = \[1\] Output: \[1\] Constraints: * The number of nodes in the tree is in the range [0, 100]. * `-100 List[int]: result = [] self.inorder_recur(root, result) return result def inorder_recur(self, node, result): if node: Traverse lef
- 100-same-tree100 Same Tree - EasyProblem: Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. Example 1: Input: p = \[1,2,3\], q = \[1,2,3\] Output: true Example 2: Input: p = \[1,2\], q = \[1,null,2\] Output: false Example 3: Input: p = \[1,2,1\], q = \[1,1,2\] Output: false Constraints: * The number of nodes in both trees is in the range [0, 100]. * `-
- 118-pascals-triangle118 Pascal's Triangle - EasyProblem: 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: Example 1: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] Example 2: Input: numRows = 1 Output: [[1]] Constraints: * 1 <= numRows <= 30 Problem Analysis: * dynamic programming Trick**: add zero at the side Solutions: class Solution(object): def generate(self, numRows): """
- 119-pascals-triangle-ii119 Pascal's Triangle II - EasyProblem: Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: Example 1: Input: rowIndex = 3 Output: \[1,3,3,1\] Example 2: Input: rowIndex = 0 Output: \[1\] Example 3: Input: rowIndex = 1 Output: \[1,1\] Constraints: * `0 List[int]: res = [[1]] for i in range(rowIndex): previous row, add 0 at the side for easy calculation te
- 125-valid-palindrome125 Valid Palindrome - EasyProblem: A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a *palindrome*, or false otherwise. Example 1: Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome. Example 2: Input: s = "race a car" Output: false Explanat
- 141-linked-list-cycle141 Linked List Cycle - EasyProblem: 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. Example 1: Input: head = \[3,2,0,-4\],
- 167-two-sum-ii167 Two Sum IIProblem: 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 List[int]: 2 pointers assumption: guaranteed solution in array l, r = 0, len(numbers)-1 while l target: r -=1 elif curSum < target: l +=1 else: return [l+1,r+1] Simila
- 169-majority-element169 Majority Element - EasyProblem: 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. Example 1: Input: nums = \[3,2,3\] Output: 3 Example 2: Input: nums = \[2,2,1,1,1,2,2\] Output: 2 Constraints: * n == nums.length * `1 int: count = 0 candidate = None for num in nums: if count == 0: candidate = num
- 191-number-of-1-bits191 Number of 1 Bits - EasyProblem: Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). Note: * Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed
- 198-house-robber198 House Robber - MediumProblem 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 th
- 200-number-of-islands200 Number of Islands - MediumProblem: Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: grid = \[ \["1","1","1","1","0"\], \["1","1","0","1","0"\], \["1","1","0","0","0"\], \["0","0","0","0","0"\] \] Output: 1 Example 2: Input: grid = \[ \["1","1","0","0","0
- 202-happy-number202 Happy Number - EasyProblem: 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. Return true if n is a happy number, and false if not. Example 1: Input: n = 19 Output: t
- 213-house-robber-ii213 House Robber II - MediumProblem: You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system 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 maximu
- 217-contains-duplicate217 Contains Duplicate - EasyProblem: 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. Example 1: Input: nums = \[1,2,3,1\] Output: true Example 2: Input: nums = \[1,2,3,4\] Output: false Example 3: Input: nums = \[1,1,1,3,3,4,3,2,4,2\] Output: true Constraints: * `1 bool: count= {} for n in nums: count[n] = count.get(n, 0) + 1 if count[n] > 1: return True return
- 219-contains-duplicate-ii219 Contains Duplicate IIProblem: 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) bool: window = set() L = 0 for R in range(len(nums)): if R - L > k: remove the window from the left window.remove(nums[L]) L += 1 if nums[R] in window: return True shift window to right window.add(nums[R]) Similar Quest
- 229-majority-element-ii229 Majority Element II - MediumProblem: Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. Example 1: Input: nums = \[3,2,3\] Output: \[3\] Example 2: Input: nums = \[1\] Output: \[1\] Example 3: Input: nums = \[1,2\] Output: \[1,2\] Constraints: * `1 List[int]: if len(nums) == 1: return nums min_count = len(nums) // 3 count = {} output = set() for n in nums: count[n] = count.get(n, 0) + 1 if count[n] >
- 231-power-of-two231 Power of Two - EasyProblem: 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. Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n = 16 Output: true Explanation: 24 = 16 Example 3: Input: n = 3 Output: false Constraints: * `-231 bool: return n>0 and (n & (n - 1)) == 0 or class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and int(
- 232-implement-queue-using-stacks232 Implement Queue using Stack - EasyProblem: Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). Implement the MyQueue class: * void push(int x) Pushes element x to the back of the queue. * int pop() Removes the element from the front of the queue and returns it. * int peek() Returns the element at the front of the queue. * boolean empty() Returns true if the queue is empty, false otherwise. Notes: * You must
- 242-valid-anagram242 Valid Anagram - EasyProblem: Given two strings s and t, return true if t is an anagram of s, and false otherwise. 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 = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Constraints: * `1 bool: return Counter(s) == Counter(t) Similar Questions
- 268-missing-number268 Missing Number - EasyProblem: 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. Example 1: Input: nums = \[3,0,1\] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range \[0,3\]. 2 is the missing number in the range since it does not appear in nums. Example 2: Input: nums = \[0,1\] Output: 2 Explanation: n = 2 since there are 2 numbers, so all numbers are in the range \[0,2\]. 2 is the miss
- 278-first-bad-version278 First Bad Version - EasyProblem: You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 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 ba
- 300-longest-increasing-subsequenceProblem: Given an integer array nums, return \the length of the longest strictly increasing\\_subsequence\_. Example 1: Input: nums = \[10,9,2,5,3,7,101,18\] Output: 4 Explanation: The longest increasing subsequence is \[2,3,7,101\], therefore the length is 4. Example 2: Input: nums = \[0,1,0,3,2,3\] Output: 4 Example 3: Input: nums = \[7,7,7,7,7,7,7\] Output: 1 Constraints: * `1 int: dp = [1] * len(nums) for i in range(len(nums)): for j in range(i): If th
- 326-power-of-three326 Power of Three - EasyProblem: Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x. Example 1: Input: n = 27 Output: true Explanation: 27 = 33 Example 2: Input: n = 0 Output: false Explanation: There is no x where 3x = 0. Example 3: Input: n = -1 Output: false Explanation: There is no x where 3x = (-1). Constraints: * `-231 bool: return n > 0 and int(math.log10(n) / math.log10(3)) == (m
- 337-house-robber-iii337 House Robber - MediumProblem: The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root. Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night. Given the root of the binary tree, return the maximum amount of money the thief can rob *without alerting the
- 342-power-of-four342 Power of Four - EasyProblem: 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. Example 1: Input: n = 16 Output: true Example 2: Input: n = 5 Output: false Example 3: Input: n = 1 Output: true Constraints: * `-231 bool: return n>0 and log(n,4) %1 == 0 Similar Questions 231-power-of-two 326-power-of-three
- 344-reverse-string344 Reverse String - EasyProblem: Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory. Example 1: Input: s = \["h","e","l","l","o"\] Output: \["o","l","l","e","h"\] Example 2: Input: s = \["H","a","n","n","a","h"\] Output: \["h","a","n","n","a","H"\] Constraints: * `1 None: """ Do not return anything, modify s in-place instead. """ s[:] = s[::-1] Similar Que
- 349-intersection-of-two-arrays349 Intersection of Two Arrays - EasyProblem: 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. Example 1: Input: nums1 = \[1,2,2,1\], nums2 = \[2,2\] Output: \[2\] Example 2: Input: nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\] Output: \[9,4\] Explanation: \[4,9\] is also accepted. Constraints: * `1 List[int]: #return set([value for value in nums1 if value in nums2]) return set(nums1).intersectio
- 350-intersection-of-two-arrays-ii350 Intersection of Two Arrays II - EasyProblem: Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. Example 1: Input: nums1 = \[1,2,2,1\], nums2 = \[2,2\] Output: \[2,2\] Example 2: Input: nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\] Output: \[4,9\] Explanation: \[9,4\] is also accepted. Constraints: * `1 List[int]: counter1 = Counter(nums1) counter2 = Counter(nu
- 374-guess-number-higher-or-lower374 Guess Number Higher or Lower - EasyProblem: We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num), which returns three possible results: * -1: Your guess is higher than the number I picked (i.e. num > pick). * 1: Your guess is lower than the number I picked (i.e. `num int: class Solution: def gues
- 389-find-the-difference389 Find the Difference - EasyProblem: 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. Example 1: Input: s = "abcd", t = "abcde" Output: "e" Explanation: 'e' is the letter that was added. Example 2: Input: s = "", t = "y" Output: "y" Constraints: * `0 str: counter1 = Counter(s) counter2 = Counter(t) return x for x in (Counter(t) - Counter(s)).keys() res = list(Coun
- 455-assign-cookiesProblem: 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. Example 1: Input: g = \
- 463-island-perimeterProblem: You are given row x col grid representing a map where gridi = 1 represents land and gridi = 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 d
- 494-target-sum494 Target Sum - MediumProblem: You are given an integer array nums and an integer target. You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers. * For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1". Return the number of different expressions that you can build, which evaluates to target. Example 1: Input: nums = \[1,1,1,1,1\], target = 3
- 509-fibonacci-number509 Fibonacci Number - EasyProblem: The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given n, calculate F(n). Example 1: Input: n = 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. Example 2: Input: n = 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. Example 3: Input: n = 4 Output: 3 Explanation: F(4) = F
- 543-diameter-of-binary-tree543 Diameter of Binary Tree - EasyProblem: 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. The length of a path between two nodes is represented by the number of edges between them. Example 1: Input: root = \[1,2,3,4,5\] Output: 3 Explanation: 3 is the length of the path \[4,2,1,3\] or \[5,2,1,3\]. Example 2: Input: root = \[1,2\] Output: 1 C
- 617-merge-two-binary-tree617 Merge Two Binary Tree - EasyProblem: 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. Return the merged tree. Note: The merging process must start from the root nod
- 645-set-mismatchProblem: 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. You are given an integer array nums representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return them in the form of an array. Example 1: Input: nums = \[
- 649-dota2-senate649 Dota 2 Senate - MediumProblem: In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights: Ban one senator's right:** A senator can make another senator lose all his rights in this and all the following rounds. Announce the victory:** If this senator found the s
- 606-construct-string-from-binary-tree606 Construct String From Binary Tree - EasyProblem: Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. Example 1: Input: root = \[1,2,3,4\] Output: "1(2(4))(3)" Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. A
- 661-image-smootherProblem: An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). Given an m x n integer matrix img representing the grayscale of an image, return the image after a
- 682-baseball-game682 Baseball Game - EasyProblem: You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record. You are given a list of strings operations, where operations[i] is the ith operation you must apply to the record and is one of the following: * An integer x. * Record a new score of x. * '+'. * Record a new score that is the sum of the previous two scores. * 'D'. * Record a new score that is the double of the previous score. * 'C'. * Invalidate th
- 867-transpose-matrix867 Transpose Matrix - EasyProblem: Given a 2D integer array matrix, return the *transpose* of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. Example 1: Input: matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] Output: \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] Example 2: Input: matrix = \[\[1,2,3\],\[4,5,6\]\] Output: \[\[1,4\],\[2,5\],\[3,6\]\] Constraints: * m == matrix.length * n == matrix[i].length * `1 List[List[int]]: return [matrix[
- 872-leaf-similar-trees872 Leaf-Similar Trees - EasyProblem: Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence. For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. Example 1: Input: root1 = \[3,5,1,6,2,9,8,null,null,7,4\], root2 = \[3,5,1,6,7,4,2,null,nul
- 876-middle-of-the-linked-list876 Middle of the Linked List - EasyProblem: Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node. Example 1: Input: head = \[1,2,3,4,5\] Output: \[3,4,5\] Explanation: The middle node of the list is node 3. Example 2: Input: head = \[1,2,3,4,5,6\] Output: \[4,5,6\] Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. Constraints: * The number of nodes in the list is in the range [1, 10
- 888-fair-candy-swap888 Fair Candy Swap - EasyProblem: Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of
- 896-monotonic-array896 Monotonic Array - EasyProblem: An array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i = nums[j]. Given an integer array nums, return true if the given array is monotonic, or false otherwise. Example 1: Input: nums = \[1,2,2,3\] Output: true Example 2: Input: nums = \[6,5,4,4\] Output: true Example 3: Input: nums = \[1,3,2\] Output: false Constraints: * `1 bool: increasing, decreasing = True, True for i in range(l
- 935-knight-dialer935 Knight Dialer - MediumProblem: The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the chess diagram below: We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell). Given an integer n, return how many
- 938-rangesum-of-bst938 Range Sum of BSTProblem: Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the *inclusive* range [low, high]. Example 1: Input: root = \[10,5,15,3,7,null,18\], low = 7, high = 15 Output: 32 Explanation: Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32. Example 2: Input: root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10 Output: 23 Explanation: Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10
- 946-validate-stack-sequences946 Validate Stack Sequence - MediumProblem: Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise. Example 1: Input: pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] Output: true Explanation: We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 Example 2: Input: pushed = \[1,2,3,4,5\], poppe
- 977-squares-of-a-squared-arrayProblem: Given an integer array nums sorted in non-decreasing order, return an array of *the squares of each number* sorted in non-decreasing order. Example 1: 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\] Constraints: * `1 List[int]: return sorted(i*i for i in nums) Solution 2 class Solution:
- 997-find-the-town-judgeProblem: In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: 1. The town judge trusts nobody. 1. Everybody (except for the town judge) trusts the town judge. 1. There is exactly one person that satisfies properties 1 and 2. You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi. If a trust relationship does not exist in tru
- 983-minimum-cost-for-tickets983 Minimum Cost For Tickets - MediumProblem: You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365. Train tickets are sold in three different ways: * a 1-day pass is sold for costs[0] dollars, * a 7-day pass is sold for costs[1] dollars, and * a 30-day pass is sold for costs[2] dollars. The passes allow that many days of consecutive travel. * For example, if we get a 7-day pass on day 2, then we can tra
- 1051-height-checker1051 Height Checker - EasyProblem: A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line. You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed). Return the *number of indic
- 1122-relative-sort-arrayRelative Sort ArrayProblem: Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. Example 1: Input: arr1 = \[2,3,1,3,2,4,6,7,9,2,19\], arr2 = \[2,1,4,3,9,6\] Output: \[2,2,2,1,4,3,3,9,6,7,19\] Example 2: Input: arr1 = \[28,6,22,8,44,17\], arr2 = \[22,28,8,6\] Outp
- 1137-n-th-tribonacci-numberProblem: The Tribonacci sequence Tn is defined as follows: T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. Given n, return the value of Tn. Example 1: Input: n = 4 Output: 4 Explanation: T_3 = 0 + 1 + 1 = 2 T_4 = 1 + 1 + 2 = 4 Example 2: Input: n = 25 Output: 1389537 Constraints: * `0 int: if n in self.memo: return self.memo[n] self.memo[n] = self.tribonacci(n-1) + self.tribonacci(n-2) + self.tribonacci(n-3) return self.memo[n] Si
- 1155-number-of-dice-rolls-with-target-sum1155 Number of Dice Rolls With Target Sum - MediumProblem: You have n dice, and each die has k faces numbered from 1 to k. Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice, so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7. Example 1: Input: n = 1, k = 6, target = 3 Output: 1 Explanation: You throw one die with 6 faces. There is only one way to get a sum of 3. Example 2: Input: n = 2, k = 6, target = 7 Output: 6
- 1160-find-words-that-can-be-formed-by-characters1160 Find Words That Can Be Formed By Characters - EasyProblem: You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words. Example 1: Input: words = \["cat","bt","hat","tree"\], chars = "atach" Output: 6 Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6. Example 2: Input: words = \["hello","world","leetcode"\], chars = "welldonehoneyr" Output: 1
- 1207-unique-number-of-occurencesProblem: Given an array of integers arr, return true if the number of occurrences of each value in the array is *unique* or false otherwise. Example 1: Input: arr = \[1,2,2,1,1,3\] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. Example 2: Input: arr = \[1,2\] Output: false Example 3: Input: arr = \[-3,0,1,-3,1,1,1,-3,10,0\] Output: true Constraints: * `1 bool: c1 = Counter(arr) return len
- 1232-check-if-it-is-a-straight-line1232 Check If It Is a Straight Line - EasyProblem: You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\] Output: true Example 2: ** Input: coordinates = \[\[1,1\],\[2,2\],\[3,4\],\[4,5\],\[5,6\],\[7,7\]\] Output: false Constraints: * `2 bool: if len(coordinates) <= 2: return True calculate slope x0
- 1235-maximum-profit-in-job-scheduling1235 Maximum Profit in Job Scheduling - HardProblem: We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. If you choose a job that ends at time X you will be able to start another job that starts at time X. Example 1: ** Input: startTime = \[1,2,3,3\], endTime = \[3,4,5,6\], profit = \[50,10,40,70\
- 1266-minimum-time-visiting-all-points1266 Minimum Time Visiting All Points - EasyProblem: On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the *minimum time* in seconds to visit all the points in the order given by points. You can move according to these rules: * In 1 second, you can either: * move vertically by one unit, * move horizontally by one unit, or * move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second). * You have to visit the points in the same order as they
- 1287-element-appearing-more-than-25-in-sorted-array128 Element Appearing More Than 25% In Sorted Array - EasyProblem: Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. Example 1: Input: arr = \[1,2,2,6,6,6,6,7,10\] Output: 6 Example 2: Input: arr = \[1,1\] Output: 1 Constraints: * `1 int: n = len(arr) quarter = n // 4 for i in range(n - quarter): if arr[i] == arr[i + quarter]: return arr[i] Similar Questions
- 1347-minimum-number-of-steps-to-make-two-strings-anagram1347 Minimum Number of Steps to Make Two Strings Anagram - MediumProblem: You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character. Return the minimum number of steps to make t an anagram of s. An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. Example 1: Input: s = "bab", t = "aba" Output: 1 Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s. Example 2: Input: s = "leetcode", t = "pra
- 1396-design-underground-system1396 Design Underground System - MediumProblem: An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the UndergroundSystem class: * void checkIn(int id, string stationName, int t) * A customer with a card ID equal to id, checks in at the station stationName at time t. * A customer can only be checked into one place at a time. * void checkOut(int id, string stationName,
- 1422-maximum-score-after-splitting-a-string1422 Maximum Score After Splitting a String - EasyProblem: Given a string s of zeros and ones, return the maximum score after splitting the string into two *non-empty* substrings (i.e. left substring and right substring). The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring. Example 1: Input: s = "011101" Output: 5 Explanation: All possible ways of splitting s into two non-empty substrings are: left = "0" and right = "11101", score = 1 + 4 = 5 left = "01" and right =
- 1424-diagonal-traverse-ii1424 Diagonal Traverse II - MediumProblem: Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images. Example 1: Input: nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] Output: \[1,4,2,7,5,3,8,6,9\] Example 2: Input: nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\] Output: \[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16\] Constraints: * `1 List[int]: m = [] for i, row in enumerate(nums): for j, v in enumerate(row): if i
- 1436-destination-city1436 Destination City - EasyProblem: You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city. Example 1: Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] Output: "Sao Paulo" Explanation: Starting at "Londo
- 1464-maximum-product-of-two-elements-in-an-array1464 Maximum Product of Two Elements in an Array - EasyProblem: Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). Example 1: Input: nums = \[3,4,5,2\] Output: 12 Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)(nums\[2\]-1) = (4-1)(5-1) = 3\*4 = 12. Example 2: Input: nums = \[1,5,4,5\] Output: 16 Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get t
- 1496-path-crossing1496 Path Crossing - EasyProblem: Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path. Return true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise. Example 1: Input: path = "NES" Output: false Explanation: Notice that the path doesn't cross any point more tha
- 1512-number-of-good-pairs1512 Number of Good Pairs - EasyProblem: Given an array of integers nums, return the number of *good pairs*. A pair (i, j) is called good if nums[i] == nums[j] and i \ int: res = 0 count = {} for n in nums: if n in count: res+= count[n] count[n] +=1 else: count[n] =1 return res class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count = {} res = 0 for n in nums:
- 1531-string-compression-ii1531 String Compression II - HardProblem: Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3". Notice that in this problem, we are not adding '1' after single characters. Given a string s and an
- 1544-make-the-string-great1544 Make The String Great - EasyProblem: Given a string s of lower and upper case English letters. A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: * `0 "aAcC" --> "cC" --> "" "abBAcC" --> "abBA" --> "aA" --> "" Example 3: Input: s = "s" Output: "s" Constraints: * `1 str: stack = [] for char in s: if stack: Check if the last character in the stack is of opposite case if (char.islower() and stack[-1] == char.upper()) or (char.isu
- 1557-minimum-number-of-vertices-to-reach-all-nodes1557 Minimum Number of Vertices to Reach All NodesProblem: Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi. Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists. Notice that you can return the vertices in any order. Example 1: Input: n = 6, edges = \[\[0,1\],\[0,2\],\[2,5\],\[3,4\],\[4,2\]\] Output: \[0,3\] Explanation: It's not possibl
- 1561-maximum-number-of-coins-you-can-get1561 Maximum Number of Coins You Can Get - MediumProblem: There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose any 3 piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the maximum number of coins. * Your friend Bob will pick the last pile. * Repeat until there are no more piles of coins. Given an array of integers piles where piles[i] is the number of co
- 1578-minimum-time-to-make-rope-colorful1578 Minimum Time to Make Rope Colorful - MediumProblem: Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon. Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope. Return the
- 1582-special-positions-in-a-binary-matrix1582 Special Positions in a Binary Matrix - EasyProblem: Given an m x n binary matrix mat, return the number of special positions in mat. A position (i, j) is called special if mati == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed). Example 1: Input: mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\] Output: 1 Explanation: (1, 2) is a special position because mat\[1\]\[2\] == 1 and all other elements in row 1 and column 2 are 0. Example 2: Input: mat = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\] Output: 3 Explanat
- 1608-special-array-with-x-elements-greater-than-or-equal-x1608 Special Array with X Elements Greater Than Or Equal X - EasyProblem: You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x. Notice that x does not have to be an element in nums. Return x if the array is *special, otherwise, return* -1. It can be proven that if nums is special, the value for x is **unique. Example 1: Input: nums = \[3,5\] Output: 2 Explanation: There are 2 values (3 and 5) that are greater than or e
- 1624-largest-substring-between-two-equal-characters1624 Largest Substring Between Two Equal Characters - EasyProblem: Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. Example 1: Input: s = "aa" Output: 0 Explanation: The optimal substring here is an empty substring between the two 'a's. Example 2: Input: s = "abca" Output: 2 Explanation: The optimal substring here is "bc". Example 3: Input: s = "cbzxy" Output: -1 Ex
- 1630-arithmetic-subarrays1630 Arithmetic Subarrays - MediumProblem: A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i. For example, these are arithmetic sequences: 1, 3, 5, 7, 9 7, 7, 7, 7 3, -1, -5, -9 The following sequence is not arithmetic: 1, 1, 2, 5, 7 You are given an array of n integers, nums, and two arrays of m integers each, l and r
- 1637-widest-vertical-area-between-two-points-containing-no-points1637 Widest Vertical Area Between Two Points Containing No Points - MediumProblem: Given n points on a 2D plane where points[i] = [xi, yi], Return the *widest vertical area* between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. Example 1: Input: points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\] Output: 1 Expl
- 1646-get-maximum-in-generated-array1646 Get Maximum in Generated Array - EasyProblem: You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way: * nums[0] = 0 * nums[1] = 1 * nums[2 * i] = nums[i] when 2 <= 2 * i <= n * nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n Return the *maximum* integer in the array nums. Example 1: Input: n = 7 Output: 3 Explanation: According to the given rules: nums\[0\] = 0 nums\[1\] = 1 nums\[(1 * 2) = 2\] = nums\[1\] = 1 nums\[(1 * 2) + 1 = 3\] = nums\[1\] + nums\
- 1657-determine-if-two-strings-are-close1657 - Determine if Two Strings are Close - MediumProblem: Two strings are considered close if you can attain one from the other using the following operations: * Operation 1: Swap any two existing characters. * For example, abcde -> aecdb * Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. * For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's) You can use the operations on either string as many times as necessary. Giv
- 1662-check-if-two-string-arrays-are-equivalent1662 Check if Two String Arrays are Equivalent - EasyProblem: Given two string arrays word1 and word2, return true if the two arrays *represent* the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. Example 1: Input: word1 = \["ab", "c"\], word2 = \["a", "bc"\] Output: true Explanation: word1 represents string "ab" + "c" -> "abc" word2 represents string "a" + "bc" -> "abc" The strings are the same, so return true. Example 2: Input: word1 = \["a", "cb"\], word2
- 1688-count-of-matches-in-tournament1688 Count of Matches in Tournament - EasyProblem: You are given an integer n, the number of teams in a tournament that has strange rules: * If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. * If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round. Return the number of matche
- 1700-number-of-students-unable-to-eat-lunch1700 Number of Students Unable to Eat LucnchProblem: The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step: * If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue. * Otherwise, they w
- 1704-determine-if-string-halves-are-alike1704 Determine if String Halves Are Alike - EasyProblem: You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. Return true if a and b are *alike*. Otherwise, return false. Example 1: Input: s = "book" Output: true Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowe
- 1716-calculate-money-in-leetcode-bankProblem: Hercy wants to save money for his first car. He puts money in the Leetcode bank every day. He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday. Given n, return the total amount of money he will have in the Leetcode bank at the end of the nth day. Example 1: Input: n = 4 Output: 10 Explanation: After the 4th day, the total is 1 +
- 1758-minimum-changes-to-make-alternating-binary-string1758 Minimum Changes To Make Alternating Binary String - EasyProblem: You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not. Return the *minimum* number of operations needed to make s alternating. Example 1: Input: s = "0100" Output: 1 Explanation: If you change the last character to '1', s will be "0101", which is altern
- 1759-count-number-of-homogenous-substrings1759 Count Number of Homogenous Substrings - MediumProblem: Given a string s, return the number of *homogenous* substrings of s. Since the answer may be too large, return it modulo 109 + 7. A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string. Example 1: Input: s = "abbcccaa" Output: 13 Explanation: The homogenous substrings are listed as below: "a" appears 3 times. "aa" appears 1 time. "b" appears 2 times. "bb" appears 1 time. "c" appears 3 time
- 1791-find-center-of-star-graph1791 Find Center of Star Graph - EasyProblem: There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph. Example 1: Input: edges = \[\[1,2\],\[2,3\],\[4,2\]\] Output: 2 Explanation: As shown in the figure ab
- 1814-count-nice-pairs-in-an-array1814 Count Nice Pairs in an Array - MediumProblem: You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions: * `0 int: MOD = 10**9 + 7 freq = {} res = 0 for num in nums: calculate diff between num and its reverse diff = num - int(str(num)[::-1]) freq[diff] = freq.get(diff,
- 1838-frequency-of-the-most-frequent-element1838 Frequency of the Most Frequent Element - MediumProblem: The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1. Return the *maximum possible frequency* of an element after performing *at most* k operations. Example 1: Input: nums = \[1,2,4\], k = 5 Output: 3 Explanation: Increment the first element three times and the second element two times to make nums = \[4,4,4\]. 4
- 1845-seat-reservation-manager1845 Seat Reservation Manager - MediumProblem: Design a system that manages the reservation state of n seats that are numbered from 1 to n. Implement the SeatManager class: * SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available. * int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number. * void unreserve(int seatNumber) Unreserves the seat with the given seatNumber. Example 1: Input \["SeatManager", "reserve"
- 1846-maximum-element-after-decreasing-and-rearrangingProblem: You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions: * The value of the first element in arr must be 1. * The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, `abs(arr[i] - arr[i - 1]) int: n = len(arr) arr.sort() max_val = 1 for i in range(1, n): max_val = min(arr[i], max_val + 1) return max_val
- 1863-sum-of-all-subset-xor-totals1863 Sum of All Subset XOR Totals - EasyProblem: The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty. * For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1. Given an array nums, return the *sum* of all *XOR totals* for every *subset* of nums. Note: Subsets with the same elements should be counted multiple times. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Example 1: Input: nums = \[1,3\] Ou
- 1877-minimize-maximum-pair-sum-in-array1877 Minimize Maximum Pair Sum in Array - MediumProblem: The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8. Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: Each element of nums is in exactly one pair, and The maximum pair sum is minimized. Return the minimized maximum pair sum after optimally pairing up the el
- 1887-reduce-operations-to-make-the-array-elements-equal1887 Reduce Operations to Make the Array Elements Equal - MediumProblem: Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps: 1. Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i. 1. Find the next largest value in nums strictly smaller than largest. Let its value be nextLargest. 1. Reduce nums[i] to nextLargest. Return the number of operations to make all elements in nums
- 1897-redistribute-characters-to-make-all-strings-equal1897 Redistribute Characters to Make All Strings Equal - EasyProblem: You are given an array of strings words (0-indexed). In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j]. Return true if you can make *every* string in words *equal using any number of operations, *and false otherwise. Example 1: Input: words = \["abc","aabc","bc"\] Output: true Explanation: Move the first 'a' in words[1] to the front of words[2], to make words[1] = "abc" and wo
- 1899-merge-triplets-to-form-target-triplet1899 Merge Triplets to Form Target Triplet - MediumProblem: A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain. To obtain target, you may apply the following operation on triplets any number of times (possibly zero): * Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)]. * For exam
- 1903-largest-odd-number-in-string1903 Largest Odd Number in String - EasyProblem: You are given a string num, representing a large integer. Return the *largest-valued odd* integer (as a string) that is a *non-empty substring* of num, or an empty string "" if no odd integer exists. A substring is a contiguous sequence of characters within a string. Example 1: Input: num = "52" Output: "5" Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number. Example 2: Input: num = "4206" Output: "" Explanation: There are no odd numbers
- 1913-maximum-product-difference-between-two-pairs1913 Maximum Product Difference Between Two Pairs - EasyProblem: The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). * For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16. Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized. Return the *maximum* such product difference. Example 1: Input: nums = \[5,6,2,7,4\] Output: 34 Explanation: We can choose in
- 1921-eliminate-maximum-number-of-monsters1921 Eliminate Maximum Number of Monsters - MediumProblem: You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city. The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute. You have a weapon that, once fully charged, can
- 1930-unique-length-3-palindromic-subsequences1930 Unique Length 3 Palindromic Subsequences MediumProblem: Given a string s, return the number of *unique palindromes of length three* that are a *subsequence* of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. * For example, "ace
- 1945-sum-of-digits-of-string-after-convert1945 Sum of Digits of String After Convert - EasyProblem: You are given a string s consisting of lowercase English letters, and an integer k. First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total. For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations: Convert**: "zbax" ➝ "(26)(
- 1971-find-if-path-exists-in-graphProblem: There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. You want to determine if there is a valid path that exists from vertex source to vertex destination. Given edges and the integers
- 1980-find-unique-binary-string1980 Find Unique Binary String - MediumProblem: Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that *does not appear* in nums. If there are multiple answers, you may return *any* of them. Example 1: Input: nums = \["01","10"\] Output: "11" Explanation: "11" does not appear in nums. "00" would also be correct. Example 2: Input: nums = \["00","01"\] Output: "11" Explanation: "11" does not appear in nums. "10" would also be correct. Example 3: Input: nums =
- 2000-reverse-prefix-of-word2000 Reverse Prefix of Word - EasyProblem: Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. * For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd". Return the resulting string. Example 1: Input: word = "abcdefd", ch = "d" Output: "dcbaefd" Ex
- 2053-kth-distinct-string-in-an-array2053 Kth Distinct String in an Array - EasyProblem: A distinct string is a string that is present only once in an array. Given an array of strings arr, and an integer k, return the kth distinct string** present in* arr. If there are **fewer** than k distinct strings, return *an **empty string "". Note that the strings are considered in the order in which they appear in the array. Example 1: Input: arr = \["d","b","c","b","c","a"\], k = 2 Output: "a" Explanation: The only distinct strings in arr are "d" and "a". "d" appears 1st, so
- 2073-time-needed-to-buy-tickets2073 Time Needed to Buy Tickets - EasyProblem: There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line. You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i]. Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tic
- 2101-detonate-the-maximum-bombsProblem: You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb. The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range. You may choose to detonate a single bomb. When a bomb is detonated, it will d
- 2108-find-first-palindrome-string-in-the-array2108Problem: Given an array of strings words, return the first *palindromic* string in the array. If there is no such string, return an *empty string* "". A string is palindromic if it reads the same forward and backward. Example 1: Input: words = \["abc","car","ada","racecar","cool"\] Output: "ada" Explanation: The first string that is palindromic is "ada". Note that "racecar" is also palindromic, but it is not the first. Example 2: Input: words = \["notapalindrome","racecar"\] Output: "race
- 2125-number-of-laser-beams-in-a-bankProblem: Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: * The two devices are located on two different rows: r1 and r2, where `r1 int:
- 2147-number-of-ways-to-divide-a-long-corridor2147 Number of Ways to Divide a Long Corridor - HardProblem: Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (`1 count * recusively perform dfs * base case: if w
- 2215-find-the-difference-of-two-arrays2215 Find the Difference of Two Arrays - EasyProblem: Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where: * answer[0] is a list of all *distinct* integers in nums1 which are *not* present in nums2. * answer[1] is a list of all *distinct* integers in nums2 which are *not* present in nums1. Note that the integers in the lists may be returned in any order. Example 1: Input: nums1 = \[1,2,3\], nums2 = \[2,4,6\] Output: \[\[1,3\],\[4,6\]\] Explanation: For nums1, nums1\[1\] = 2 is present at index 0 o
- 2248-intersection-of-multiple-arrays2248 Intersection of Multiple ArraysProblem: Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in *each array* of nums sorted in *ascending order*. Example 1: Input: nums = \[\[3,1,2,4,5\],\[1,2,3,4\],\[3,4,5,6\]\] Output: \[3,4\] Explanation: The only integers present in each of nums\[0\] = \[3,1,2,4,5\], nums\[1\] = \[1,2,3,4\], and nums\[2\] = \[3,4,5,6\] are 3 and 4, so we return \[3,4\]. Example 2: Input: nums = \[\[1,2,3\],\[4,5,
- 2264-largest-3-same-digit-number-in-string2264 Largest 3-Same-Digit Number in String - EasyProblem: You are given a string num representing a large integer. An integer is good if it meets the following conditions: * It is a substring of num with length 3. * It consists of only one unique digit. Return the *maximum good* integer as a *string* or an empty string "" if no such integer exists. Note: * A substring is a contiguous sequence of characters within a string. * There may be leading zeroes in num or a good integer. Example 1: Input: num = "6777133339" Output: "777" Explana
- 2331-evaluate-boolean-binary-treeProblem: You are given the root of a full binary tree with the following properties: Leaf nodes** have either the value 0 or 1, where 0 represents False and 1 represents True. Non-leaf nodes** have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND. The evaluation of a node is as follows: * If the node is a leaf node, the evaluation is the value of the node, i.e. True or False. * Otherwise, evaluate the node's two children and apply the boolean opera
- 2385-amount-of-time-for-binary-tree-to-be-infected2385 Amount of Time for Binary Tree to Be Infected - MediumProblem: You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start. Each minute, a node becomes infected if: * The node is currently uninfected. * The node is adjacent to an infected node. Return the number of minutes needed for the entire tree to be infected. Example 1: Input: root = \[1,5,3,null,4,10,6,9,2\], start = 3 Output: 4 Explanation: The following nodes are infected during: * Minute 0: Nod
- 2391-minimum-amount-of-time-to-collect-garbage2391 Minimum Amount of Time to Collect Garbage - MediumProblem: You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1 minute. You are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1. There are three garbage trucks in the ci
- 2353-design-a-food-rating-system2353 Design a Food Rating System MediumProblem: Design a food rating system that can do the following: Modify** the rating of a food item listed in the system. * Return the highest-rated food item for a type of cuisine in the system. Implement the FoodRatings class: * FoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food items are described by foods, cuisines and ratings, all of which have a length of n. * foods[i] is the name of the ith food, * cuisines[i] is the type of cuisine of t
- 2373-largest-local-values-in-a-matrixProblem: You are given an n x n integer matrix grid. Generate an integer matrix maxLocal of size (n - 2) x (n - 2) such that: * maxLocali is equal to the largest value of the 3 x 3 matrix in grid centered around row i + 1 and column j + 1. In other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid. Return the generated matrix. Example 1: Input: grid = \[\[9,9,8,1\],\[5,6,2,6\],\[8,2,6,4\],\[6,2,2,2\]\] Output: \[\[9,9\],\[8,6\]\] Explanation: The diagram
- 2418-sort-the-people2418 Sort the People - EasyProblem: You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n. For each index i, names[i] and heights[i] denote the name and height of the ith person. Return names sorted in *descending* order by the people's heights. Example 1: Input: names = \["Mary","John","Emma"\], heights = \[180,165,170\] Output: \["Mary","Emma","John"\] Explanation: Mary is the tallest, followed by Emma and John. Example 2: Input: na
- 2441-largest-positive-integer-that-exists-with-its-negativeProblem: Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array. Return the positive integer k. If there is no such integer, return -1. Example 1: Input: nums = \[-1,2,-3,3\] Output: 3 Explanation: 3 is the only valid k we can find in the array. Example 2: Input: nums = \[-1,10,6,7,-7,1\] Output: 7 Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value. Example 3
- 2485-find-the-pivot-integer2485 Find the Pivot Integer - EasyProblem: Given a positive integer n, find the pivot integer x such that: * The sum of all elements between 1 and x inclusively equals the sum of all elements between x and n inclusively. Return the pivot integer x. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input. Example 1: Input: n = 8 Output: 6 Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21. Example 2: Input: n = 1 Output: 1 Explana
- 2540-minimum-common-value2540 Minimum Common Value - EasyProblem: Given two integer arrays nums1 and nums2, sorted in non-decreasing order, return the *minimum integer common* to both arrays. If there is no common integer amongst nums1 and nums2, return -1. Note that an integer is said to be common to nums1 and nums2 if both arrays have at least one occurrence of that integer. Example 1: Input: nums1 = \[1,2,3\], nums2 = \[2,4\] Output: 2 Explanation: The smallest element common to both arrays is 2, so we return 2. Example 2: Input: nums1 = \[1
- 2610-convert-an-array-into-a-2d-array-with-conditions2610 Convert an Array Into a 2D Array With Conditions - MediumProblem: You are given an integer array nums. You need to create a 2D array from nums satisfying the following conditions: * The 2D array should contain only the elements of the array nums. * Each row in the 2D array contains distinct integers. * The number of rows in the 2D array should be minimal. Return the resulting array. If there are multiple answers, return any of them. Note that the 2D array can have a different number of elements on each row. Example 1: Input: nums = \[1,3,4,1,2,
- 2706-buy-two-chocolates2706 Buy Two Chocolates - EasyProblem: You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money. You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy. Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy
- 2864-maximum-odd-binary-number2864 Maximum Odd Binary Number - EasyProblem: You are given a binary string s that contains at least one '1'. You have to rearrange the bits in such a way that the resulting binary number is the maximum odd binary number that can be created from this combination. Return a string representing the maximum odd binary number that can be created from the given combination. Note that the resulting string can have leading zeros. Example 1: Input: s = "010" Output: "001" Explanation: Because there is just one '1', it must be in the
- 2870-minimum-number-of-operations-to-make-array-empty2870 Minimum Number of Operations to Make Array Empty - MediumProblem: You are given a 0-indexed array nums consisting of positive integers. There are two types of operations that you can apply on the array any number of times: * Choose two elements with equal values and delete them from the array. * Choose three elements with equal values and delete them from the array. Return the *minimum* number of operations required to make the array empty, or -1 if it is not possible. Example 1: Input: nums = \[2,3,3,2,2,4,2,3,4\] Output: 4 Explanation: We can
- 3005-count-elements-with-maximum-frequency3005 Count Elements with Maximum Frequency - EasyProblem: You are given an array nums consisting of positive integers. Return the *total frequencies* of elements in nums such that those elements all have the *maximum* frequency. The frequency of an element is the number of occurrences of that element in the array. Example 1: Input: nums = \[1,2,2,3,1,4\] Output: 4 Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array. So the number of elements in the array with maximum frequency is 4. Exampl