0% found this document useful (0 votes)
2 views

Coding Challenge March-1

The document contains a series of coding statements that describe various algorithmic problems, including finding the majority element in an array, determining the longest subarray of 1's after deleting one element, and calculating the maximum water container from vertical lines. Each problem includes input examples, expected outputs, and constraints on the input values. The problems cover a range of topics such as arrays, strings, linked lists, and binary trees.

Uploaded by

rutujapatil6007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Coding Challenge March-1

The document contains a series of coding statements that describe various algorithmic problems, including finding the majority element in an array, determining the longest subarray of 1's after deleting one element, and calculating the maximum water container from vertical lines. Each problem includes input examples, expected outputs, and constraints on the input values. The problems cover a range of topics such as arrays, strings, linked lists, and binary trees.

Uploaded by

rutujapatil6007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Coding Statement 1: Majority Element

Given an array nums of size n, return the majority element.


The majority element is the element that appears more than ⌊n / 2⌋ times. n / 2⌋ times. 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 <= n <= 5 * 104
-109 <= nums[i] <= 109

Coding Statement 2: Longest Subarray of 1's After Deleting One


Element.

Given a binary array nums, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1's in
the resulting array. Return 0 if there is no such subarray.

Example 1:
Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3
numbers with value of 1's.
Example 2:
Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1]
longest subarray with value of 1's is [1,1,1,1,1].
Example 3:
Input: nums = [1,1,1]

Page 1 of 20
Output: 2
Explanation: You must delete one element.

Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1.

Coding Statement 3: Container With Most Water

You are given an integer array height of length n. There are n vertical
lines drawn such that the two endpoints of the ith line are (i, 0) and (i,
height[i]).
Find two lines that together with the x-axis form a container, such that the
container contains the most water. Return the maximum amount of water
a container can store.
Notice that you may not slant the container.

Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array
[1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the
container can contain is 49.
Example 2:
Input: height = [1,1]
Output: 1
Constraints:
n == height.length
2 <= n <= 105
0 <= height[i] <= 104

Coding Statement 4: Is Subsequence

Given two strings s and t, return true if s is a subsequence of t, or false


otherwise.

Page 2 of 20
A subsequence of a string is a new string that is formed from the original
string by deleting some (can be none) of the characters without disturbing
the relative positions of the remaining characters. (i.e., "ace" is a
subsequence of "abcde" while "aec" is not).

Example 1:
Input: s = "abc", t = "ahbgdc"
Output: true
Example 2:
Input: s = "axc", t = "ahbgdc"
Output: false

Constraints:
0 <= s.length <= 100
0 <= t.length <= 104
s and t consist only of lowercase English letters

Coding Statement 5: Removing Stars From a String

You are given a string s, which contains stars *.

In one operation, you can:

Choose a star in s.
Remove the closest non-star character to its left, as well as remove the
star itself.
Return the string after all stars have been removed.

Note:
The input will be generated such that the operation is always possible.
It can be shown that the resulting string will always be unique.

Example 1:
Input: s = "leet**cod*e"
Output: "lecoe"
Explanation: Performing the removals from left to right:

Page 3 of 20
- The closest character to the 1st star is 't' in "leet**cod*e". s becomes
"lee*cod*e".
- The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes
"lecod*e".
- The closest character to the 3rd star is 'd' in "lecod*e". s becomes
"lecoe".
There are no more stars, so we return "lecoe".
Example 2:
Input: s = "erase*****"
Output: ""
Explanation: The entire string is removed, so we return an empty string.
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters and stars *.
The operation above can be performed on s.

Coding Statement 6: Odd Even Linked List

Given the head of a singly linked list, group all the nodes with odd
indices together followed by the nodes with even indices, and return the
reordered list.

The first node is considered odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should
remain as it was in the input.

You must solve the problem in O(1) extra space complexity and O(n)
time complexity.
Example 1:
Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
Example 2:
Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]

Page 4 of 20
Constraints:

The number of nodes in the linked list is in the range [0, 104].
-106 <= Node.val <= 106

Coding Statement 7: Leaf-Similar Trees

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,null,null,null,null,null,9,8]
Output: true
Example 2:
Input: root1 = [1,2,3], root2 = [1,3,2]
Output: false
Constraints:
The number of nodes in each tree will be in the range [1, 200].
Both of the given trees will have values in the range [0, 200].

Coding Statement 8: Successful Pairs of Spells and Potions

You are given two positive integer arrays spells and potions, of length n
and m respectively, where spells[i] represents the strength of the ith spell
and potions[j] represents the strength of the jth potion.

You are also given an integer success. A spell and potion pair is
considered successful if the product of their strengths is at least success.

Page 5 of 20
Return an integer array pairs of length n where pairs[i] is the number of
potions that will form a successful pair with the ith spell.

Example 1:
Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7
Output: [4,0,3]
Explanation:
- 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.
- 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.
- 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.
Thus, [4,0,3] is returned.
Example 2:
Input: spells = [3,1,2], potions = [8,5,8], success = 16
Output: [2,0,2]
Explanation:
- 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.
- 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful.
- 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful.
Thus, [2,0,2] is returned.
Constraints:
n == spells.length
m == potions.length
1 <= n, m <= 105
1 <= spells[i], potions[i] <= 105
1 <= success <= 1010

Coding Statement 9: Guess Number Higher or Lower

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).

Page 6 of 20
1: Your guess is lower than the number I picked (i.e. num < pick).
0: your guess is equal to the number I picked (i.e. num == pick).
Return the number that I picked.

Example 1:
Input: n = 10, pick = 6
Output: 6
Example 2:
Input: n = 1, pick = 1
Output: 1
Example 3:
Input: n = 2, pick = 1
Output: 1
Constraints:
1 <= n <= 231 - 1
1 <= pick <= n

Coding Statement 10: N-th Tribonacci Number

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:

Page 7 of 20
0 <= n <= 37
The answer is guaranteed to fit within a 32-bit integer, ie. answer <=
2^31 - 1.

Coding Statement 11: Counting Bits

Given an integer n, return an array ans of length n + 1 such that for each i
(0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

Example 1:
Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10
Example 2:
Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101

Constraints:
0 <= n <= 105

Coding Statement 12 : Non-overlapping Intervals


Given an array of intervals intervals where intervals[i] = [starti, endi],
return the minimum number of intervals you need to remove to make the
rest of the intervals non-overlapping.

Note that intervals which only touch at a point are non-overlapping. For
example, [1, 2] and [2, 3] are non-overlapping.

Page 8 of 20
Example 1:
Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of the intervals are non-
overlapping.
Example 2:
Input: intervals = [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of the
intervals non-overlapping.
Example 3:
Input: intervals = [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're
already non-overlapping.
Constraints:
1 <= intervals.length <= 105
intervals[i].length == 2
-5 * 104 <= starti < endi <= 5 * 104

Coding Statement 13: Daily Temperatures

Given an array of integers temperatures represents the daily temperatures,


return an array answer such that answer[i] is the number of days you have
to wait after the ith day to get a warmer temperature. If there is no future
day for which this is possible, keep answer[i] == 0 instead.

Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90]

Page 9 of 20
Output: [1,1,0]
Constraints:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100

Coding Statement 14: Min Cost Climbing Stairs

You are given an integer array cost where cost[i] is the cost of ith step on
a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.

Example 1:
Input: cost = [10,15,20]
Output: 15
Explanation: You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
Example 2:
Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6
Explanation: You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.

Constraints:
2 <= cost.length <= 1000
0 <= cost[i] <= 999
-----------------------------------------------------------------------------------------
Coding Statement 15: Letter Combinations of a Phone Number

Page 10 of 20
Given a string containing digits from 2-9 inclusive, return all possible
letter combinations that the number could represent. Return the answer in
any order.
A mapping of digits to letters (just like on the telephone buttons) is given
below. Note that 1 does not map to any letters.

Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = ""
Output: []
Example 3:
Input: digits = "2"
Output: ["a","b","c"]
Constraints:
0 <= digits.length <= 4
digits[i] is a digit in the range ['2', '9'].

Coding Statement 16: The k-th Lexicographical String of All Happy


Strings of Length n

A happy string is a string that:

consists only of letters of the set ['a', 'b', 'c'].


s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-
indexed).
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy
strings and strings "aa", "baa" and "ababbc" are not happy strings.
Given two integers n and k, consider a list of all happy strings of length n
sorted in lexicographical order.
Return the kth string of this list or return an empty string if there are less
than k happy strings of length n.
Example 1:
Input: n = 1, k = 3
Output: "c"

Page 11 of 20
Explanation: The list ["a", "b", "c"] contains all happy strings of length 1.
The third string is "c".
Example 2:
Input: n = 1, k = 4
Output: ""
Explanation: There are only 3 happy strings of length 1.
Example 3:
Input: n = 3, k = 9
Output: "cab"
Explanation: There are 12 different happy string of length 3 ["aba", "abc",
"aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You
will find the 9th string = "cab"
Constraints:
1 <= n <= 10
1 <= k <= 100

Coding Statement 17: First Bad Version


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 bad. Implement a function to find the first bad version. You
should minimize the number of calls to the API.
Example 1:
Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
Example 2:
Input: n = 1, bad = 1

Page 12 of 20
Output: 1
Constraints:
1 <= bad <= n <= 231 - 1
-------------------------------------------------------------------------- --
Coding Statement 18: Nim Game

You are playing the following Nim Game with your friend:
Initially, there is a heap of stones on the table.
You and your friend will alternate taking turns, and you go first.
On each turn, the person whose turn it is will remove 1 to 3 stones from
the heap.
The one who removes the last stone is the winner.
Given n, the number of stones in the heap, return true if you can win the
game assuming both you and your friend play optimally, otherwise return
false.
Example 1:
Input: n = 4
Output: false
Explanation: These are the possible outcomes:
1. You remove 1 stone. Your friend removes 3 stones, including the last
stone. Your friend wins.
2. You remove 2 stones. Your friend removes 2 stones, including the last
stone. Your friend wins.
3. You remove 3 stones. Your friend removes the last stone. Your friend
wins.
In all outcomes, your friend wins.
Example 2:
Input: n = 1
Output: true
Example 3:

Input: n = 2
Output: true

Constraints:
1 <= n <= 231 - 1

Page 13 of 20
Coding Statement 19: Binary Watch
A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6
LEDs on the bottom to represent the minutes (0-59). Each LED
represents a zero or one, with the least significant bit on the right.

For example, the below binary watch reads "4:51".

Given an integer turnedOn which represents the number of LEDs that are
currently on (ignoring the PM), return all possible times the watch could
represent. You may return the answer in any order.
The hour must not contain a leading zero.

For example, "01:00" is not valid. It should be "1:00".


The minute must consist of two digits and may contain a leading zero.
For example, "10:2" is not valid. It should be "10:02".

Example 1:
Input: turnedOn = 1
Output:
["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]
Example 2:
Input: turnedOn = 9
Output: []
Constraints:
0 <= turnedOn <= 10

Coding Statement 20: Self Dividing Numbers

A self-dividing number is a number that is divisible by every digit it


contains.

For example, 128 is a self-dividing number because 128 % 1 == 0, 128 %


2 == 0, and 128 % 8 == 0.
A self-dividing number is not allowed to contain the digit zero.

Given two integers left and right, return a list of all the self-dividing
numbers in the range [left, right] (both inclusive).

Page 14 of 20
Example 1:
Input: left = 1, right = 22
Output: [1,2,3,4,5,6,7,8,9,11,12,15,22]
Example 2:
Input: left = 47, right = 85
Output: [48,55,66,77]

Constraints:
1 <= left <= right <= 104

Coding Statement 21: Flood Fill

You are given an image represented by an m x n grid of integers image,


where image[i][j] represents the pixel value of the image. You are also
given three integers sr, sc, and color. Your task is to perform a flood fill
on the image starting from the pixel image[sr][sc].

To perform a flood fill:


Begin with the starting pixel and change its color to color.
Perform the same process for each pixel that is directly adjacent (pixels
that share a side with the original pixel, either horizontally or vertically)
and shares the same color as the starting pixel.
Keep repeating this process by checking neighboring pixels of the
updated pixels and modifying their color if it matches the original color
of the starting pixel.
The process stops when there are no more adjacent pixels of the original
color to update.
Return the modified image after performing the flood fill.
Example 1:

Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2

Output: [[2,2,2],[2,2,0],[2,0,1]]

Explanation:

Page 15 of 20
From the center of the image with position (sr, sc) = (1, 1) (i.e., the red
pixel), all pixels connected by a path of the same color as the starting
pixel (i.e., the blue pixels) are colored with the new color.

Note the bottom corner is not colored 2, because it is not horizontally or


vertically connected to the starting pixel.

Example 2:
Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0

Output: [[0,0,0],[0,0,0]]

Explanation:
The starting pixel is already colored with 0, which is the same as the
target color. Therefore, no changes are made to the image.
Constraints:
m == image.length
n == image[i].length
1 <= m, n <= 50
0 <= image[i][j], color < 216
0 <= sr < m
0 <= sc < n

Coding Statement 22: Smallest Sufficient Team


In a project, you have a list of required skills req_skills, and a list of
people. The ith person people[i] contains a list of skills that the person
has.

Consider a sufficient team: a set of people such that for every required
skill in req_skills, there is at least one person in the team who has that
skill. We can represent these teams by the index of each person.

For example, team = [0, 1, 3] represents the people with skills people[0],
people[1], and people[3].
Return any sufficient team of the smallest possible size, represented by
the index of each person. You may return the answer in any order.

It is guaranteed an answer exists.

Page 16 of 20
Example 1:
Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],
["nodejs"],["nodejs","reactjs"]]
Output: [0,2]
Example 2:
Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"],
people = [["algorithms","math","java"],["algorithms","math","reactjs"],
["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],
["aws","java"]]
Output: [1,2]

Constraints:
1 <= req_skills.length <= 16
1 <= req_skills[i].length <= 16
req_skills[i] consists of lowercase English letters.
All the strings of req_skills are unique.
1 <= people.length <= 60
0 <= people[i].length <= 16
1 <= people[i][j].length <= 16
people[i][j] consists of lowercase English letters.
All the strings of people[i] are unique.
Every skill in people[i] is a skill in req_skills.
It is guaranteed a sufficient team exists.

Coding Statement 23: Make Array Strictly Increasing

Given two integer arrays arr1 and arr2, return the minimum number of
operations (possibly zero) needed to make arr1 strictly increasing.
In one operation, you can choose two indices 0 <= i < arr1.length and 0
<= j < arr2.length and do the assignment arr1[i] = arr2[j].
If there is no way to make arr1 strictly increasing, return -1.
Example 1:
Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
Output: 1
Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7].
Example 2:

Page 17 of 20
Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1]
Output: 2
Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4,
6, 7].
Example 3:
Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
Output: -1
Explanation: You can't make arr1 strictly increasing.
Constraints:
1 <= arr1.length, arr2.length <= 2000
0 <= arr1[i], arr2[i] <= 10^9

Coding Statement 24: Design Skiplist

Design a Skiplist without using any built-in libraries.

A skiplist is a data structure that takes O(log(n)) time to add, erase and
search. Comparing with treap and red-black tree which has the same
function and performance, the code length of Skiplist can be
comparatively short and the idea behind Skiplists is just simple linked
lists.
For example, we have a Skiplist containing [30,40,50,60,70,90] and we
want to add 80 and 45 into it. The Skiplist works this way:
Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons

You can see there are many layers in the Skiplist. Each layer is a sorted
linked list. With the help of the top layers, add, erase and search can be
faster than O(n). It can be proven that the average time complexity for
each operation is O(log(n)) and space complexity is O(n)
See more about Skiplist: https://en.wikipedia.org/wiki/Skip_list
Implement the Skiplist class:
Skiplist() Initializes the object of the skiplist.
bool search(int target) Returns true if the integer target exists in the
Skiplist or false otherwise.
void add(int num) Inserts the value num into the SkipList.
bool erase(int num) Removes the value num from the Skiplist and returns
true. If num does not exist in the Skiplist, do nothing and return false. If
there exist multiple num values, removing any one of them is fine.

Page 18 of 20
Note that duplicates may exist in the Skiplist, your code needs to handle
this situation.

Example 1:

Input
["Skiplist", "add", "add", "add", "search", "add", "search", "erase",
"erase", "search"]
[[], [1], [2], [3], [0], [4], [1], [0], [1], [1]]
Output
[null, null, null, null, false, null, true, false, true, false]

Explanation
Skiplist skiplist = new Skiplist();
skiplist.add(1);
skiplist.add(2);
skiplist.add(3);
skiplist.search(0); // return False
skiplist.add(4);
skiplist.search(1); // return True
skiplist.erase(0); // return False, 0 is not in skiplist.
skiplist.erase(1); // return True
skiplist.search(1); // return False, 1 has already been erased.

Constraints:
0 <= num, target <= 2 * 104
At most 5 * 104 calls will be made to search, add, and erase.

Coding Statement 25 :Maximum Profit in Job Scheduling

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.

Page 19 of 20
Example 1:
Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
Output: 120
Explanation: The subset chosen is the first and fourth job.
Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.
Example 2:
Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit =
[20,20,100,70,60]
Output: 150
Explanation: The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
Example 3:

Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]


Output: 6
Constraints:
1 <= startTime.length == endTime.length == profit.length <= 5 * 104
1 <= startTime[i] < endTime[i] <= 109
1 <= profit[i] <= 104

Page 20 of 20

You might also like