View allAll Photos Tagged interviewprep

Problem statement

In the problem " Student Attendance Record I" we are given a string where each letter represents the attendance detail of a student. The interpretation of letters in the string is as follows:

 

- 'A' means absent.

- 'P' means present.

- 'L' means late

 

The student will be rewarded based on his attendance if he is not absent for more than one day or not late continuously for more than two days. Our task is to determine if the student will be rewarded or not.

Example

str="PPALLP"

true

Explanation:

 

As the student is not absent for more than one day and not late continuously for more than two days so he must be rewarded.

Approach for Student Attendance Record I Leetcode Solution

Implementation

This is a basic implementation problem. We need to find out if the student will be rewarded or not. So to reward the student we need to check if he is not absent for more than one day and not late continuously for more than two days. We will follow these steps to perform this check:

 

- Initialize number of 'A' count and 'L' count by zero

- Traverse the complete string.

 

- If the current character is 'A' then increment the count of 'A' by one.

- If the current character is 'L' then increment the count of 'L' by one.

- Otherwise, the count of 'L' becomes zero.

- Now check if the count of 'A' is greater than or equal to 2 or the count of 'L' is greater than 2. If the condition is true return false.

 

www.tutorialcup.com/leetcode-solutions/student-attendance...

Problem Statement

Given two binary strings a and b, we have to add these two strings and then return the result as a binary string. Binary string are the strings that contains only 0s and 1s.

Example

a = "11", b = "1"

"100"

a = "1010", b = "1011"

"10101"

Approach

 

For adding two binary strings we have to perform addition bit by bit. As we know addition is performed from right end moving towards left bits. Therefore we have to reverse the given strings first and then we can perform addition of its bits starting from index 0.

For storing bit addition sequence we can create a string variable res and append the sum of two bits and carry at end of the res string for each bit position. Finally we will return the res string for output.

Algorithm

 

- Reverse the given strings.

- Create an empty string and a carry variable. Initialise carry with 0.

- Now iterate over the given string in a while loop and add bit of first and second string along with carry. Now according to value of addition append the resultant bit to res string and also update the carry for next bit .

- At last we have output string but it is in reverse order because we have performed addition on reversed input string for our convenience. Therefore reverse the output string and finally return it.

 

Implementation

C++ Program for Add Binary Leetcode Solution

#include

using namespace std;

 

string addBinary(string a, string b)

{

int carry=0;

string res="";

 

reverse(a.begin(),a.

 

www.tutorialcup.com/leetcode-solutions/add-binary-leetcod...

Linked lists are quite like arrays in their linear properties. We can merge two sorted arrays to form an overall sorted array. In this problem, we have to merge two sorted linked lists in place to return a new list which contains elements of both lists in a sorted fashion.

Example

 

L1 = 1 -> 2 -> 9

L2 = 1 -> 3 -> 4

1 1 2 3 4 9

Approach

The simplest way to do it would be to use the two-pointer technique. Create a new empty list. Append the smaller elements among both the pointers and increment the corresponding pointer. This is a good approach but requires the creation of an extra list that consumes space.

 

The Optimal Approach should consume constant space only in order to do an in-place sorting. We can follow the iterative approach. We already have the nodes stored in both the lists. Create a new list pointer and its subsequent "next pointers" should point to predefined nodes in the memory. In this process, we create no new nodes.

Algorithm(Naive Approach)

 

- Create a function mergeTwoSortedLists() that takes two list pointers as arguments

- If either of the lists is NULL, return the other one

- Create a temp variable that will point to the smaller node among heads of both lists

- Now, at least, one node is appended to our result, so one head should be incremented

- This creates a subproblem. So, call the same recursive function and append it to temp

- If List1.value < List2.value

 

- temp = new ListNode(List1.value)

 

www.tutorialcup.com/leetcode-solutions/merge-two-sorted-l...

Problem Statement

In this problem, we are given two lists in which first list is subset of second list. For each element of first list, we have to find out next greater element in the second list.

 

Example

nums1 = , nums2 =

 

Explanation:

 

for first element of list1 i.e. for 4 there is no next greater element in list2, thus its answer is -1.

for second element of list1 i.e. for 1 there is 3 greater than 1 in list 2, thus its answer is 3.

for third element of list1 i.e. for 2 there is no next greater element in list2, thus its answer is -1.

nums1 = , nums2 =

 

Approach 1 (Brute Force)

In this approach, we simply find next greater element for each element of list1 by doing linear traversal in list2 using a nested for loop.

Each element of list1 is first searched in list2, then afterwards its next greater element is searched. We are doing this by using a flag variable. For each element of list1, it is first set to false. When we have found the element in list2, it is set to true. After that, when we will find the next greater, we will set it to false again. By doing so, we will get to know that there is any next greater element in list2 for that variable or there isn't any.

 

- If the flag variable is true, it means we could not find any next greater value for that element.

- If the flag variable is false, it means that we have found one next greater value for that element.

 

So, at end of each inner loop, according to flag value we will insert -1 as our answer.

 

www.tutorialcup.com/leetcode-solutions/next-greater-eleme...

Problem Statement

In this problem, we are given n people labelled from 1 to n. We are also given a 2d array trust shows that trustth people trusts trustth people for each 0

 

www.tutorialcup.com/leetcode-solutions/find-the-town-judg...

Problem Statement

In this problem, we are given three stones at positions a, b and c. We have to make them consecutive by performing the following step one or more times.

In each step, We will pick a left stone or a right stone and put somewhere in the between the range of left to right stone.

Let's under stand this better by following picture:

 

We have to answer both the minimum and maximum number of such steps to make these stones consecutive.

Example

a = 1, b = 2, c = 5

 

Explanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.

a = 4, b = 3, c = 2

 

We cannot make any moves.

a = 3, b = 5, c = 1

 

Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.

Approach

First let's talk about how to calculate maximum steps. Can't we simply say that the number of moves will be maximum only when both the stones at extremes come closer to middle stone by 1 unit.

Thus the number of positions between left stone and mid stone + the number of position between mid stone and right stone will be our maximum number of steps to make them consecutive.

 

Now the main problem is how to calculate minimum number of steps. We can find out minimum by understanding the following conditions.

Let's call number of positions between left stone and mid stone is lspace and the number of positions between mid stone and right stone is rspace.

Only one of the following 4 situation can be said about the initial position of these stones.

 

1.

 

www.tutorialcup.com/leetcode-solutions/moving-stones-unti...

The problem Partition Array Into Three Parts With Equal Sum Leetcode Solution provides us with an array or vector and asks if there are three partitions possible of the sequence. Here, by partition we mean that is there two indices i, j such that the sum of elements from start to ith index is equal to the sum of elements from i+1 to jth index. And the sum of elements from j+1 index to the last element is also equal to the first two segments of the array. If there exist such two indices, we say the array can be partitioned into three parts with an equal sum, else no. Before moving into the solution let's see a few examples.

 

arr =

true

Explanation: Since we can divide the array into three segments of the equal sum. Thus we can say that the array can be partitioned into three equal sums. More formally, 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1.

arr =

false

Explanation: Since there is no way to divide the array into three separate sections that have the same sums. Thus the answer is false.

Approach for Partition Array Into Three Parts With Equal Sum Leetcode Solution

The problem Partition Array Into Three Parts With Equal Sum Leetcode Solution asked us if we can partition the given array into three disjoint subarrays that have equal sums. So, to solve the problem first we need to find the total sum of the array. If the total sum is not divisible by 3, then the answer is false. Because then there is no way to divide the array into three equal sub-parts.

 

www.tutorialcup.com/leetcode-solutions/partition-array-in...

In this problem, we need to find the length of the shortest path from the root to any leaf in a given binary tree. Note that the "length of the path" here means the number of nodes from the root node to the leaf node. This length is called Minimum Depth of A Binary Tree.

Example

Input

              

2

Explanation

 

The Shortest path is: 2 -> 1 , which is of length 2

 

Input

              

3

Explanation

 

The Shortest Path is: 1 -> 2 -> 3, of length 3

Approach(Recursive)

This problem is structurally same as finding the height of a binary tree but in this case, we need to find the minimum height/depth between the root and any leaf in the tree. We can retrieve the minimum depths of left and right subtrees of the root using Depth First Search(DFS) and then return the minimum of the two depths. We need to consider some cases when either of the left and right subtrees of a node is NULL. If the left subtree is NULL, it will return a height equal to 0 but as we have found no leaf in this subtree, so this 0 will be a wrong answer. Hence, we only need to call the recursive function when the node it is called upon is NOT null.

Algorithm

 

www.tutorialcup.com/leetcode-solutions/minimum-depth-of-b...

Contact number = +91 9869217917, Email Id = contact@un-klutter.com, Contact Person = Mr. Dhruv Vaishnav, City = Mumbai, Country = India.

 

www.un-klutter.com

 

Keywords - Professional resume writing, Resume writing services, Best resume writers, Affordable resume writing, Resume help, Executive resume writing, CV writing services, Cover letter writing, LinkedIn profile optimization, Job application services, Career coaching, Interview preparation, Resume makeover, Online resume services, Custom resume writing

  

Hashtags - #ResumeWriting #ResumeServices #CareerGoals #JobSearch #ResumeTips #CareerAdvice #JobHunting #CVWriting #ProfessionalResume #ResumeHelp #JobApplication #InterviewPrep #CareerCoaching #LinkedInProfile #ResumeMakeover

 

Problem Statement

In this problem, we are given a sequence of numbers (may be positive negative or zero). We have to take a positive integer with us and then we will start adding all integers of this array from left to right with it.

We want the minimum positive integer that we should take in the start, so that, at any time our current sum will always remain positive.

Example

nums =

5

Explanation:

 

We can see here that if we choose startValue=5, we get all intermediate sum positive. We can check for startValue=4 also, which is not correct solution.

nums =

1

Explanation:

 

Minimum start value should be positive.

Approach

Suppose, we have array , nums =

Now if we choose initial value as 2, and keep adding elements from left to right, then:

 

In above example, we have chosen initial value as 2. Our sum will not remain positive every time, so we need some larger element.

 

Let the initial val be 5.

 

Now, we can clearly see that if starting value is 5 then, we can surely travel throughout the array keeping our current sum positive always. 5 can be the answer if it is the smallest integer doing so.

Let's think of a situation if we choose val=0 with us at the start.

 

Now, can we say that if we overcome the value of most negative current sum (-4 in current example), then we can clearly pass the array without any problem.

Like, in above example, the most negative value is -4, To overcome it, we have to make it 1 (because, smallest positive integer needed).

 

www.tutorialcup.com/leetcode-solutions/minimum-value-to-g...

The problem Construct the Rectangle Leetcode Solution states that you are a web designer. And you are given a task to design a web page with some pre-defined area. There are some constraints imposed upon the design. The length of the web page needs to be greater or equal to the width of the web page, the area of the designed web page must be equal to the given area. Last but not the least, the difference between the length and width should be as small as possible. So, let's take a look at a few examples before diving deep into solving the problem.

 

area = 4

 

Explanation: The length and width of the web page with an area equal to 4 can be either 1x4 or 2x2. But since we need to find the length and width such that they have a minimum difference between them. It's better to choose 2x2 dimensions. The 2x2 dimension also follows that the length is greater or equal to the width of the page.

area = 23

 

Explanation: You can have only two web pages with area = 23. you can either have dimensions 23x1 or 1x23. Since the web-page with dimensions 1x23 violates our first condition. We can have the web-page with size 23x1 only.

Approach for Construct the Rectangle Leetcode Solution

The problem Construct the Rectangle Leetcode Solution asks us to find out the suitable size of the web-page with some pre-defined area. The web-page dimensions should satisfy the imposed constraints.

 

www.tutorialcup.com/leetcode-solutions/construct-the-rect...

Problem Statement

In this problem, we are given a non-negative integer. We have to convert the integer in a such a format, in which there will be some dots which separates all thousands, i.e. there are dots after each 3 places from right.

Example

#1

n = 987

"987"

#2

n = 123456789

"123.456.789"

Explanation:

 

The number is 123456789. The rightmost dot will be 3 places from right. So, seeing from right, we will leave 9,8 and 7 behind and put a dot between 6 and 7. Then after leaving 6,5 and 4 behind, we will put a dot between 3 and 4.

Now leaving 3,2 and 1 behind, we would place a dot only if there would be more number on left because . should be between two numbers according to the question.

Thus we will not place any dot.

Approach

First of all, we are converting the number into string (let str). Then we are traversing the string str from right. We are using a for loop for this. In each loop we are inserting its three digits followed by a dot.

But after each digit insertion, we will check if we have reached out of the left bound of the str. If yes, then we will break the loop. Otherwise, we will keep inserting the 3 digits and then 1 dot.

 

Note that the 3rd checking to insert a dot is the crucial one, which will be used in scenarios like 123 or 123.456 or 123.456.789 where we don't need to insert a dot before leftmost digit.

Because we are inserting the characters from right to left thus our created string needs to be reversed to get the final answer.

 

www.tutorialcup.com/leetcode-solutions/thousand-separator...

The problem Number of Students Doing Homework at a Given Time Leetcode Solution asks us to find the number of students working on their homework at a given time. The problem is very clear, the title itself is already able to explain the whole problem. We are given a query time and the time the students work on their homework. So, using this information we are asked to find the number of students who are doing their homework during the query time. So, as usual before directly jumping into the solution. Let us check a few examples.

 

startTime = , endTime = , queryTime = 4

1

Explanation: We have three students out of which only 1 student works on his/her homework during the query time. Because there is only a single child starting his homework at time = 3, and completing it at time = 7.

startTime = , endTime = , queryTime = 4

1

Explanation: We have a single student who starts his/her homework at the same as that of the query time. Thus the output is also 1.

Approach for Number of Students Doing Homework at a Given Time Leetcode Solution

The problem asked us to find the number of students who are working on their homework during the query time. We are provided with the start and end times of students' homework activities in the form of a vector or array. Using this information, we try to find the required value.

 

We can easily solve the problem just by traversing over the given information. The given information is the starting and end time of the homework activity.

 

www.tutorialcup.com/leetcode-solutions/number-of-students...

Problem statement

In the problem " Find Lucky Integer in an Array " we are given an array where an integer is called lucky if its frequency in the array is equal to its value.

 

Our task is to return the largest lucky number. If no such number exists we have to return -1. Values in the array lie between 1 and 500 and the length of the array is a maximum of 500.

Example

arr =

2

Explanation:

 

The frequency of 2 is 2 and the frequency of 3 and four is 1. As 2 is the only lucky integer so this is our answer.

Sorting Approach for Find Lucky Integer in an Array Leetcode Solution

As we want to count the number of occurrences of each number and then find the greatest element satisfying the given condition. To do this we will pick a number and then traverse the entire array to count its occurrences and then select the greatest element satisfying the condition. Here we need to traverse the complete array n times so the time complexity becomes O(n*n). We can increase the performance by sorting the array. This will bring the same numbers together. We will follow these steps:

 

- Sort the array in decreasing order.

- Count all occurrences of the encountered element if it satisfies the condition then return it.

- In the end, if no element satisfies the condition then return -1.

 

Implementation

C++ code for Find Lucky Integer in an Array

#includ

 

www.tutorialcup.com/leetcode-solutions/find-lucky-integer...

The problem Count Complete Group Leetcode Solution provides us with an integer. We are required to find the sum of digits of each number between 1 and n (inclusive). We will then group the numbers with the same sum of digits and keep a count. Then we need to compute the number of groups with the maximum count. This seems confusing at first. So, let's take a look at a few examples.

Examples

 

n = 13

4

Explanation: The numbers grouped as per the sum of their digits are , , , , , , , , . So, there are 4 groups having the maximum frequency of 2. Hence the answer, 4.

n = 2

2

Explanation: Similarly, if you see the numbers until 2. There are only 2 numbers, 1, and 2. Both create a group having a single number each. Thus the answer is 2 groups that have a maximum frequency of 1.

Approach

The problem Count Largest Group Leetcode Solution provided us with a single integer. And asked to count the number of groups of numbers having the maximum frequency where we group the numbers as per their sum of digits. Since the input is a constraint to a maximum of 10000. We create an array to keep the frequency of the sum of digits of numbers. The maximum size of the cnt array should be 36. Because the input with the maximum sum will be 36. So, we simulate the process of finding the sum of digits for each number from 1 to n. During the evaluation of frequency, we store the maximum frequency calculated until now.

 

www.tutorialcup.com/leetcode-solutions/count-largest-grou...

The problem Relative Ranks Leetcode Solution asks us to return a vector or an array of strings representing the relative ranks. We are provided with an array that represents the score obtained by athletes. Then we use the given score array to assign the ranks. There is a small change for the top 3 candidates. Instead of, assigning them simple numbers 1, 2, or 3. We need to assign Gold, Silver, and Bronze medal. Other than the top 3 candidates, we can assign them simple numbers from 4 to n. Let's take a look at a few examples.

 

Explanation: Since the given array represents the scores attained by the athletes. The athlete with the highest score will be given Gold Medal and so forth. Thus we gave Gold Medal to the athlete with a score of 3, Silver Medal to the athlete with a score of 2, and Bronze medal to the athlete with a score of 1.

 

Explanation: Since the top 3 candidates are awarded medals and the rest candidates are assigned a rank. Thus we have assigned medals to the top 3 candidates, and assigned rank 4, and 5 to the corresponding candidates.

Approach

The problem Relative Ranks Leetcode Solution asks us to assign the medals to the top 3 candidates and assign the ranks to the rest of the candidates. The simplest thing one can think of is to sort the given sequence. But we need to assign the ranks to the original indices. So, if we sort the given sequence directly, then we will miss the original indices. And will not be able to decide to assign the ranks.

 

www.tutorialcup.com/leetcode-solutions/relative-ranks-lee...

The problem Minimum Absolute Difference in BST Leetcode Solution states that you are provided with a Binary Search Tree. And you are required to find the minimum absolute difference in the entire BST. A BST or a Binary Search Tree is nothing but a tree with some nodes that follow a rule. the rule is that the left subtree of a node must contain only the nodes that have a value less than the current node. Similarly, for the right subtree, the nodes must contain values greater than the current node. So, as usual, we must first take a look at a few examples before jumping into the solution.

 

1

Explanation: The difference between the nodes , , , all have difference of 1. And all other pairs have a greater difference. Thus the answer is 1.

Brute Force Approach for Minimum Absolute Difference in BST Leetcode Solution

The problem Minimum Absolute Difference in BST Leetcode Solution asked us to find the minimum difference between any two nodes in a given Binary Search Tree. So, one way to find the answer is to pick any two vertices or nodes of the BST and calculate the difference. We will update the answer once we find a pair that has a lesser absolute difference than the previous pair. Initially, we can use any two nodes, and at the end of the process. The answer will be stored in the respective variables. So, to simulate this process, we will traverse the BST in an inorder manner and store it in a vector.

 

www.tutorialcup.com/leetcode-solutions/minimum-absolute-d...

Problem Statement

 

In this problem, we are given two numbers candies and num_people. The first number candies is the number of candies we have. num_people shows the number of person in which we have to distribute the candies.

 

The rule of candies distribution is:

We start from the leftmost person give him 1 candy then we give 2 candies to 2nd person, 3 candies to 3rd person till n candies to nth person. After that we again start from leftmost person giving him n+1 candies then n+2, n+3. This cyclic distribution continues till we run out of candies i.e. when our remaining candies will be less than current requirement, we will give the remaining candies to current person and then we stop.

 

Example

candies = 7, num_people = 4

 

Explanation:

 

On the first turn, ans += 1, and the array is .

On the second turn, ans += 2, and the array is .

Third turn, ans += 3, and the array is .

Fourth turn, ans += 1 (because there is only one candy left), and the final array is .

candies = 10, num_people = 3

 

Explanation:

 

On the first turn, ans += 1, and the array is .

On the second turn, ans += 2, and the array is .

Third turn, ans += 3, and the array is .

Fourth turn, ans += 4, and the final array is .

Approach 1 (Brute Force)

The simplest approach is to give l candy to first person and give 2 to 2nd person and so on move to last person. Then again start from first person giving him candies accordingly.

This

 

www.tutorialcup.com/leetcode-solutions/distribute-candies...

Problem Statement

In this problem, we are given a number made up of digits 6 or 9. We can replace one of a digit of this number and change this to another digit. i.e. we can replace a 6 to 9 or we can replace a 9 to 6. We have to output the maximum number we can get by at most one replace.

Example

num = 9669

9969

Explanation:

 

Changing the first digit results in 6669.

Changing the second digit results in 9969.

Similarly Changing the third digit results in 9699.

Changing the fourth digit results in 9666.

The maximum number is 9969.

9996

9999

Explanation:

 

Changing the last digit 6 to 9 results in the maximum number.

Approach

As we can replace a digit to make the number maximum, one thing we can understand here is that, we should replace 6 to 9 only, because 9 to 6 replace will make the number smaller.

Another thing we can understand here is, we should replace a digit leftmost as possible. Let's understand this thing with an example.

 

Suppose we have a number given, 6666

We have to replace a digit from 6 to 9 such that the formed number is maximum. If we replace the rightmost 6 then we get 6669.

If we replace the leftmost 6 then we get 9666 which is of course the maximum of all numbers gained by such replacement on this number.

Thus we will try to replace the leftmost 6. And if no 6 is present in given number e.g. 9999 then we will not perform any replace operation.

 

www.tutorialcup.com/leetcode-solutions/maximum-69-number-...

The problem Convert Integer to the Sum of Two No-Zero Integers Leetcode Solution asked us to partition the given integer. We should partition the given integer into two numbers. There is a constraint imposed on these two integers. These two integers should not contain the digit 0. For a better understanding, we will take a look at a few examples.

 

n = 2

 

Explanation: The two integers in the output are 1 and 1. The integers can be the same but they must not have digit 0. The constraint is met in the output. The sum of both the integers is also equal to the input. Thus the output is correct.

n = 1010

 

Explanation: The output is correct because the sum of both the integers is equal to 1010. And they also do not have any digit equal to 0.

Approach for Convert Integer to the Sum of Two No-Zero Integers Leetcode Solution

The problem asked us to partition the given input into two integers. The condition which should be met is already stated in the description above. The first condition is that the sum of the integers must be equal to the given integer. The two integers that will be returned as the output should not contain any 0 digits. To solve the problem, we run a loop over the first integer that ranges from 1 to n. The second integer can be deduced from the first relation. Then we check if both the integers satisfy the second condition.

 

For checking the second condition, we create a custom function that takes an integer as input.

 

www.tutorialcup.com/leetcode-solutions/convert-integer-to...

The problem Convert Integer to the Sum of Two No-Zero Integers Leetcode Solution asked us to partition the given integer. We should partition the given integer into two numbers. There is a constraint imposed on these two integers. These two integers should not contain the digit 0. For a better understanding, we will take a look at a few examples.

 

n = 2

 

Explanation: The two integers in the output are 1 and 1. The integers can be the same but they must not have digit 0. The constraint is met in the output. The sum of both the integers is also equal to the input. Thus the output is correct.

n = 1010

 

Explanation: The output is correct because the sum of both the integers is equal to 1010. And they also do not have any digit equal to 0.

Approach for Convert Integer to the Sum of Two No-Zero Integers Leetcode Solution

The problem asked us to partition the given input into two integers. The condition which should be met is already stated in the description above. The first condition is that the sum of the integers must be equal to the given integer. The two integers that will be returned as the output should not contain any 0 digits. To solve the problem, we run a loop over the first integer that ranges from 1 to n. The second integer can be deduced from the first relation. Then we check if both the integers satisfy the second condition.

 

For checking the second condition, we create a custom function that takes an integer as input.

 

www.tutorialcup.com/leetcode-solutions/convert-integer-to...

The problem Find the Distance Value Between Two Arrays Leetcode Solution provides us two arrays arr1 and arr2. Along with the two arrays, we are provided with an integer n. Then the problem asks us to find the relative distance between the given two arrays. The relative distance is defined as the number of elements in the first array that does not have any element in the second array that has a minimum absolute difference less than or equal to the given integer d. So as always before diving deep into the solution, first we should take a look at a few examples.

arr1 = , arr2 = , d = 2

2

Explanation: We will pick each element one by one from the first array to verify the output. For the first element, 4 we do not have any corresponding element in the second array that has a minimum absolute difference of 2 with it. The same goes for 5. But if we see the last element, 8, there exists an element with the same value in the second array. Thus 8, is not considered into the answer. The answer will thus become equal to 2 because of the first 2 elements of the first array.

Brute force Approach to Find the Distance Value Between Two Arrays Leetcode Solution

The brute force solution for the problem simply iterates over both the arrays picking unique pairs. Then these unique pairs are checked if the difference between them is less than the given integer 'd'. If the difference is less than d, we flag the element.

 

www.tutorialcup.com/leetcode-solutions/find-the-distance-...

Problem Statement

In this problem we have to find out how many trailing zeroes will be there in n!

Given n as input.

 

Like there is one trailing zero in 5!

5! = 5*4*3*2*1 = 120

Example

n = 3

0

Explanation: 3! = 6, no trailing zero

n = 0

0

Explanation: 0! = 1, no trailing zero

   

To find the number of trailing zeroes in n! , a simple way is to calculate the n! and check how many zeroes are there at the end. This we can do simply by checking if dividing the number by 10 we get remainder 0 and then removing the last zero by dividing it by 10. We can count this till we get remainder equal to zero each time.

 

But this approach is not practical with simple integers because we know n! is a very big number. In C++ and Java simple integer size is 64-bit at best which can only store an integer to a limit of 2^63 - 1. Which is approximate to 10^18. In java we can use BigInteger class to store big numbers like n!. But this brute force approach has large time and space complexity.

 

Here we are going to discuss efficient solution for finding the trailing zeroes in n!

Approach 1 (Counting factors of 5)

We can say that total number of trailing zeroes will be equal to count of how many times 10 is factor of that number. And we know that every 10 is formed of the product of two prime numbers 2 and 5.

So if we find out how many factors of 2's are there in the number. Similarly how many factors of 5's are there.

 

www.tutorialcup.com/leetcode-solutions/factorial-trailing...

Problem statement

In the problem " N-th Tribonacci Number" we are given a number n. Our task is to find out the N-th tribonacci number.

 

The zeroth tribonacci number is 0. The first tribonacci number is 1. The second tribonacci number is 1.

 

N-th tribonacci number is summation of (N-1- th tribonacci number), (N-2- th tribonacci number), and (N-3- th tribonacci number).

 

Example

n = 4

4

Explanation: As zeroth, first ,and second tribonacci numbers are 0,1,1 respectively. So the third tribonacci number is (0+1+1) 2. Likewise, the fourth tribonacci is (1+1+2) 4.

Approach for N-th Tribonacci Number Leetcode Solution

As N-th tribonacci number is defined as the summation of (N-1), (N-2), and (N-3) tribonacci number. So we first need the (N-3)-th tribonacci number this will be used in calculating (N-2), (N-1), and (N)-th tribonacci number. So now our new problem is to calculate (N-3)-th tribonacci number. Here we can conclude one thing that is to calculate the N-th tribonacci number we need to calculate one to N-th tribonacci number because every next value is dependent on the previous three values. We will follow these steps:

 

- We will store the values of zeroth, first and second tribonacci numbers in three variables namely a, b, and c respectively.

- Here a,b, and c will store the last three tribonacci numbers. Using these last three tribonacci numbers we will calculate the next tribonacci number and then update the values of a,b, and c.

 

www.tutorialcup.com/leetcode-solutions/n-th-tribonacci-nu...

The problem Assign cookies Leetcode Solution provides with two arrays. One of the arrays represents the size of the cookies and the other represents the greediness of the children. The problem states that you are the parent of children, and you want the maximum number of children to be content. You can only give one cookie to a child. Find the maximum number of content children. Let's take a few examples first.

g = , s =

1

Explanation: We have two cookies of size 1 each, and three children with different content values. We can make only a single child content that has greediness value 1. Since the other two children require larger cookies.

 

g = , s =

2

Explanation: We can make both of the children feel content because the cookies that we have are greater or equal to the required sizes. Thus the output is 2.

Approach for Assign Cookies Leetcode Solution

The problem Assign Cookies Leetcode Solution asks us to find the maximum number of content children if we can give only a single cookie to a child. Thus the best approach is to greedily try to make the least greedy child feel content with the smallest cookie that can be used. So, to simulate this process we sort both the given arrays and try to assign the cookies to the children. If we can't assign the current cookie to the current child then we try the next cookie until we satisfy the current child. Because if we can not satisfy the current child, we cannot satisfy the next children with the current cookie.

 

www.tutorialcup.com/leetcode-solutions/assign-cookies-lee...

The problem Distance Between Bus Stops Leetcode Solution provides us an array of integers describing the distance between the adjacent cities. The cities are given in a circular order. So, the last city is followed by the first city. Now, we are required to find out the minimum distance between the two given cities. So, before moving onto the solution. Let's see a few examples.

 

distance = , start = 0, destination = 1

1

Explanation: The cities arranged in circular order are shown in the image above. Here, in the example, we are provided city 0 as the starting city and city 1 as the destination. So, there are two ways possible to start from city 0 and reach city1. Either we can simply go from city 0 to 1. Or we can follow the path from 0 to 3, 3 to 2, 2 to 1. Now, we will calculate the distance to be traveled from both ways and return the minimum distance. The first path 0 to 1, requires us to travel distance = 1, while the other path requires us to travel distance = 9. Thus the minimum distance is 1 unit.

distance = , start = 0, destination = 2

3

Explanation: Just as we did in the above example, we calculate the distance in both directions, and return the minimum. Since the two paths are of length 3 and 7. We pick the minimum of the two that is 3.

Approach for Distance Between Bus Stops Leetcode Solution

The problem Distance Between Bus Stops Leetcode Solution asked to find the minimum distance required to travel if starting city and destination city are given to us.

 

www.tutorialcup.com/leetcode-solutions/distance-between-b...

The problem Replace Elements with Greatest Element on Right Side Leetcode Solution provides us with an array or vector of integers. The problem asked us to replace all the elements with the element that is greatest among all the elements on the right side. So consider if we had an array or sequence, {a, b, c}. If the numbers follow the trend, b > c> a. So, as per the question, the output should be {b, c, -1}. Before diving deep into the solution, let's check a few examples.

 

Explanation: The output is easy to understand because each element has been replaced by the greatest element on the right of it.

 

Explanation: Since there is no element to the right of the current number. Thus we return -1 as output.

Approach for the Replace Elements with Greatest Element on Right Side Leetcode Solution

The problem states the problem clearly by its name itself. The problem says to replace each element with the greatest element that occurs on the right side of it. Now, the only that is left to do is to simulate the process. We can easily do this if we start traversing the array from the right side. So, instead of going from the left side, we start from the right side. We keep an element that stores the maximum element found until now. We store the current element in a variable, then keep on updating the maximum value. At this point, we can replace the current element with the greatest element/maximum element.

Code

 

www.tutorialcup.com/leetcode-solutions/replace-elements-w...

Problem Statement

In this problem, we have to design a parking lot. We have 3 kinds of parking spaces (big, medium and small). All these parking spaces has some fixed number of empty slots initially.

Like, in big type of space, we can place at most b cars. In small type of space, we can place at most s cars and in medium type of space, we can place m cars.

 

We are given the values b, s and m (maximum limit of all three spaces) in the constructor of the given class. Now, we have to place some cars in these spaces. The cars too are of three types big small and medium. And they can only be placed into their respective parking lot. Like small car can only be placed in small parking lot.

 

We have to find out if we can place these cars or not. For this purpose we have to create a function addCar(int type) which will return true if the car of this type can be placed or not else this will return false.

 

Example

 

, , , , ]

 

Explanation:

 

1. parkingSystem.addCar(1); // return true because there is 1 available slot for a big car

2. parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car

3. parkingSystem.addCar(3); // return false because there is no available slot for a small car

4. parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.

Approach

We have to do two task here. One is to use the values given to the constructor. Another is to create function addCar().

Now,

 

www.tutorialcup.com/leetcode-solutions/design-parking-sys...

Problem Statement

In this problem, we are given n people labelled from 1 to n. We are also given a 2d array trust shows that trustth people trusts trustth people for each 0

 

www.tutorialcup.com/leetcode-solutions/find-the-town-judg...

Problem Statement

In this problem, we are given three stones at positions a, b and c. We have to make them consecutive by performing the following step one or more times.

In each step, We will pick a left stone or a right stone and put somewhere in the between the range of left to right stone.

Let's under stand this better by following picture:

 

We have to answer both the minimum and maximum number of such steps to make these stones consecutive.

Example

a = 1, b = 2, c = 5

 

Explanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.

a = 4, b = 3, c = 2

 

We cannot make any moves.

a = 3, b = 5, c = 1

 

Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.

Approach

First let's talk about how to calculate maximum steps. Can't we simply say that the number of moves will be maximum only when both the stones at extremes come closer to middle stone by 1 unit.

Thus the number of positions between left stone and mid stone + the number of position between mid stone and right stone will be our maximum number of steps to make them consecutive.

 

Now the main problem is how to calculate minimum number of steps. We can find out minimum by understanding the following conditions.

Let's call number of positions between left stone and mid stone is lspace and the number of positions between mid stone and right stone is rspace.

Only one of the following 4 situation can be said about the initial position of these stones.

 

1.

 

www.tutorialcup.com/leetcode-solutions/moving-stones-unti...

In this problem, we have to find the sum of all left leaves in a binary tree. A leaf that is called a "Left Leaf" if it is a left child of any node in the tree.

 

Example

2

 

/

 

4 7

 

/

 

9 4

Sum is 13

2

   

3

Sum is 0

Approach

We can use recursion to traverse the binary tree. If any node has a left child and it is a leaf too, we can add the value of the left child to our sum. But this approach uses the recursive stack space.

 

Can we use any other traversal that can save the memory space?

 

Morris Inorder Traversal can be implemented to visit every node iteratively. Check if it has a left leaf child and add its value accordingly in the result. This is the optimal approach. Note that we can implement "Morris Inorder traversal" only if the problem allows us to change the structure of the tree.

Algorithm(Recursive)

 

- Create a function sumOfLeftLeaves() that returns the sum of left leaves of any passed root

- If the root of the tree is NULL

 

- return zero

 

- If the current root has a left child and it is a leaf

 

- return its value + sumOfLeftLEaves(root->left) + sumOfLeftLeaves(root->right)

 

- Return sumOfLeftLEaves(root->left) + sumOfLeftLeaves(root->right)

 

Algorithm (Morris Inorder)

 

- Traverse the binary using Morris Inorder Traversal:

 

- Thread the inorder predecessor of the left subtree of any node to itself.

 

www.tutorialcup.com/leetcode-solutions/sum-of-left-leaves...

Problem Statement

In this problem, we are given an array of strings. We need to find which strings in the given array belong to any same row in the QWERTY keyboard as shown below:

 

We assume that the array contains strings of English letters.

Example

String_Array = {"Anand" , "Soni" , "Ashfak" , "Turipo"}

Ashfaq Turipo

String_Array = {"qaz" , "wsx" , "edc"}

No words found

Approach(Hashing)

The approach is pretty straightforward. We can hash all the indices to their rows and check that every character for every string in the array has the same value hashed to it. But we need to hash for all 26 characters first in order to preprocess the hashing part. Based on that, we can store them in an array and return it.

Algorithm

 

- Create a HashMap rowId and an array result to store resultant strings

- Initialize a boolean variable same_row = true to run checks on strings

- Hash all the characters to their rows

- For every string str in the array:

 

- set same_row = true

- For every character chr in the array starting from the second:

 

- If the rowId is not equal to rowId:

 

- set same_row = false and jump to next string

 

- If same_row == true:

 

- Push it to result

 

- Return result

 

Implementation of Keyboard Row Leetcode Solution

C++ Program

#includ

 

www.tutorialcup.com/leetcode-solutions/keyboard-row-leetc...

The problem Increasing Decreasing String Leetcode Solution states that we are given a string as input. We need to modify the input. Or as the question states, we need to sort it. The term sort here does not necessarily mean simply sorting the characters. We will sort the string in a specific order of first arranging the letters in strictly increasing order until we reach the increasing character. And as we reach the largest character, we start to arrange letters in strictly decreasing order starting with the largest character available. We need to repeat this process until the entire string's characters have been used. So as usual, let's first check a few examples.

 

s = "aaaabbbbcccc"

"abccbaabccba"

Explanation: As stated above the sorted string must follow a certain pattern. First, the characters must be in a strictly increasing pattern and then in decreasing pattern. The output here follows the same pattern. The string starts with a and follows a strictly increasing pattern until c. Then again starting with c ends with a. The process is repeated until the letters of the input string are exhausted.

s = "rat"

"art"

Explanation: The sorted (resultant) string starts with the smallest character and follows the same pattern until we are left with no characters.

Approach for Increasing Decreasing String Leetcode Solution

The problem Increasing Decreasing String Leetcode Solution asked us to sort the given input string in a certain fashion.

 

www.tutorialcup.com/leetcode-solutions/increasing-decreas...

The problem Convert a Number to Hexadecimal Leetcode Solution provides us with an integer. Then asks us to convert the given integer in decimal number system to hexadecimal number system. More formally, the question requires us to convert an integer given in base 10 to a base 16 representation. We had already solved a problem where we were given a number in the decimal number system. And had to convert it into base 7. So, before moving on further, let's take a look at a few examples.

Example

26

1a

 

Explanation: This conversion is easy, if happen to know about the hexadecimal number system. But if you are unaware of it, just convert the given number into base 16 representation. We do that by repetitive division and storing remainder. One thing to note that, 10 is represented using 'a' in hexadecimal notation.

-1

ffffffff

Explanation: Since the negative numbers are stored as their 2's complement notation. The -1 in its 2s complement notation is 11111111111111111111111111111111. So, we just convert this into hexadecimal which is shown in the output.

Approach for Convert a Number to Hexadecimal Leetcode Solution

Before diving deep into the problem Convert a Number to Hexadecimal Leetcode Solution. Let's first familiarize ourselves with the hexadecimal number system. So, the hexadecimal number system is also like the decimal number system but the numbers 10 to 15 are represented using lower-case alphabets from 'a' to 'f'.

 

www.tutorialcup.com/leetcode-solutions/convert-a-number-t...

In this problem, we are given a Binary Search Tree and an integer. We need to find the address of a node with value same as the given integer. As a check, we need to print the preorder traversal of the sub-tree that has this node as root. If there is no value same as the given integer in the tree, we need to return NULL, i.e, an empty tree.

Example

2

 

/

 

1 3

   

4

 

Target Value = 3

3 4

5

 

/

 

1 10

 

Target Value = 4

Empty BST

Explanation #1

 

BST contains a node with value 3, so we return its sub-tree and print its preorder traversal.

 

Explanation #2

 

BST doesn't contain any node with value 4, so we return NULL and print "Empty BST".

Approach(Recursive)

Let us think of how a problem depends on subproblem in this case. Let say our function returns the address of node with target value, if found. We start from the root of the tree. If this node is NULL, it is obvious we have reached the end of the binary search tree and hence there is no node with target value. So, we return NULL. Similarly, we the node value is equal to the target value, we return this node. Otherwise, we know that the target-valued node will either be in left subtree or right subtree of current root. We can decide the direction(left or right) by comparing root.value and target value. So, we call the same recursive function with root as root.left or root.right.

 

www.tutorialcup.com/leetcode-solutions/search-in-a-binary...

Problem statement

In the problem " Find Words That Can Be Formed by Characters" we are given an array of strings that consists of lower case English alphabets (words) and a string that consists of a set of characters (chars).

 

Our task is to check for each string in the array if it can be formed using the characters of chars (we can use each character of char only once). In the end, we need to return the sum of the length of all the strings which can be formed using characters of chars string.

Example

words = , chars = "welldonehoneyr"

10

Explanation:

 

In this example, we can form hello and world using the characters of the chars string. So the total length of hello and world is 5+5=10.

Approach for Find Words That Can Be Formed by Characters Leetcode Solution

To solve this problem we will use a frequency array and that will store the count of characters present in the string. We will follow these steps to solve the problem:

 

- Create a frequency array and store the frequency of characters of the chars string.

- Now check each string of word array one by one.

 

- Create a copy of the frequency array.

- Now check each character of the selected string. If the frequency of a character in the frequency array is less than 1 then we can not form a selected string using the characters of the chars string else decrease the character frequency by 1.

 

www.tutorialcup.com/leetcode-solutions/find-words-that-ca...

Problem Statement

In this problem, we need to find the difference between the product of digits and the sum of digits of a given positive integer.

Example

1234

14

Explanation: Product = 4 * 3 * 2 * 1 = 24 and Sum = 4 + 3 + 2 + 1 = 10. So, the difference is 14

2045

-11

Explanation: Product = 2 * 0 * 4 * 5 = 0 and Sum = 2 + 0 + 4 + 5 = 11. So, the difference is -11.

Approach

It becomes easy to return the desired output if we could extract out the digits from the integer one by one. This can be easily done by using the '%' operator, as " % 10 " fetchs us the last digit of an integer, we can then divide the integer by 10 to pop the last digit out of it(as we did it in this problem). In this way, we can process each digit and find the product and the sum. Then, we can return the difference between them to get the required result.

 

Algorithm

 

- Initialize two variables, product = 1 and sum = 0 to store the product and sum of digits of integer N respectively

- Follow these steps until N > 0:

 

- Multiply the last digit of N to product, product *= N % 10

- Add the last digit of N to sum, sum += N % 10

- Divide N by 10 to drop the last digit, N /= 10

 

- Return product - sum

 

Implementation of Subtract the Product and Sum of Digits of an Integer Leetcode Solution

C++ Program

#includ

 

www.tutorialcup.com/leetcode-solutions/subtract-the-produ...

The problem Compare Strings by Frequency of the Smallest Character Leetcode Solution, states that we define a function f(s) over a non-empty string s such that f(s) is equal to the frequency of the smallest character in the string. Then we are given some words and some queries. for each query, we are required to find the number of words such that f(words) > f(query_word). Then we have to return the answer for all the queries as a vector or an array. So, before diving deep into the solution, let's take a look at a few examples.

queries = , words =

 

Explanation: f("zaaaz") = 3, because the smallest character is 'a' that has a frequency equal to 3, while f("cbd") = 1. So, we have only a single word that has f(i) > f(query_word).

 

queries = , words =

 

Explanation: So, after calculation of the value of the defined function for all the given words. We find f("a") = 1, f("aa") = 2, f("aaa") = 3, f("aaaa") = 4. After evaluating the value of function for the words given in the queries, we find f("bbb") = 3, f("cc") = 2. So, then we find that for the word f("bbb"), we have a single word "aaaa" that has function value greater than 3. Similarly, for the word "cc", we have words "aaa", "aaaa" that have greater function value.

Approach

 

www.tutorialcup.com/leetcode-solutions/compare-strings-by...

We are given an integer and the goal is to check whether the integer is a power of two, that is, it can be represented as some whole power of '2'.

 

Example

16

Yes

13

No

Approach

A trivial solution can be: Check if all prime factors of the integer are all '2'. The time complexity of this method would be O(log2N). In order to do it in an optimal way, we can take help of Bit manipulations.

 

"Any number which is a power of two can only have a single bit set in binary representation"

 

How can it be checked that there is only a single bit set in the binary form?

 

Consider any number, x.

 

Now, if x is some power of two, then (x - 1) will turn off all the right bits to the set bit(set them as '0') and the set bit would be unset.

 

x = 8, x - 1 = 7

 

So, using BITWISE-AND of x and (x - 1), we can say if a number is some power of two, then, x & (x - 1) = 0

Algorithm(Trivial)

 

- Keep dividing the number by '2' until it is not divisible by '2' anymore.

- If the number is equal to '1':

 

- The integer is a power of two

 

- Else

 

- The integer is not a power of two

 

Algorithm(Bit-Manipulation)

 

- Check if x & (x - 1) is equal to zero

 

- If yes, the number is a power of 2

- The integer is not a power of 2, otherwise

 

Implementation

C++ Program of Power of Two Leetcode Solution

Naive Method

#includ

 

www.tutorialcup.com/leetcode-solutions/power-of-two-leetc...

Problem Statement

In this problem, we are given a list of string. We have to find out the characters that are common in all the strings. If a character is present in all strings in multiple times, then we have to output the character multiple times.

Suppose, we have array of strings

 

We can see that, character 'e' is present once in all strings, l is present twice in all strings. No other character is common.

So, in our output list, character 'e' will be present once and character 'l' will be present twice.

Example

 

Approach

We can see that we have to find out the common frequency of characters a-z in all strings here.

For every string we can create a count array of size 26, which is having frequency of characters a-z. index 0 will have count of 'a' in that string and index 1 has count of 'b' and so on.

Now for each character from a to z, we have to find out the minimum count which may be present in any of the arrays created above. We are doing this, because we are interested in minimum presence of a character in all strings. In other words, we are only taking common characters from each string.

   

So, we will firstly create an ans array of size 26 which is having all indexes set at max value.

Then, we will traverse the array of strings from left to right. In each step, we will create the count array for current string. Then we will compare the current created array with ans array.

Because

 

www.tutorialcup.com/leetcode-solutions/find-common-charac...

As the title says, the goal is to find the third maximum integer in a given array of integers. Note that we need to find the distinct third maximum integer in the array. We return the maximum integer in the array when it has no distinct third maximum integer.

Example

Array = {1 , 3 , 2 , -2 , -4 , -9}

1

Explanation

The first maximum is 3, second maximum is 2 and third maximum is 1. So, we print 1.

Array = {1 , 1 , 3}

3

Explanation

The first maximum is 3, second maximum is 1, but there is no third maximum because we consider both the 1s as the second maximum here.

Approach(Sorting)

We can sort the whole array and find the third distinct integer starting from its back. Note that we can't return Array simply as there can be duplicate entries in the array. If we do not find 3 distinct integers in the array, we return its last element as it is the maximum element. Follow the given algorithm for better understanding.

 

Algorithm

 

- Create a function thirdMax() returning the required integer

- thirdMax() returns the third distinct maximum integer in a given array- a

- Sort the array

- Initialize a variable, idx to store the last index of the array and distinctCount to count the distinct elements from the back

- while idx >= 0:

 

- Increment distinctCount

 

- Initialize i to iterate through indices having the same value as a

- while the elements before idx have the same value as a and i >= 0:

 

- Decrement i

 

- If i == -1, it means that we have

 

www.tutorialcup.com/leetcode-solutions/third-maximum-numb...

Problem Statement

In this problem an array of integers is given and we have to find out the count of total number of good pairs (a, a) where a=a.

Example

nums =

4

Explanation: There are 4 good pairs at indices (0,3), (0,4), (3,4), (2,5) .

 

6

Explanation: Each pair in the array are good.

Approach (Brute Force)

In the given problem we can use two loop, one for a and second for a of the pair. In this nested loop we will iterate for all possible combination for the pair (a, a) and check whether a is equal to a or not.

 

Algorithm:

 

1. Create a count variable and initialize with zero.

2. Run a nested loop, outer loop for a from i=0 to i=n-1 and inner loop for a from j=i+1 to j=n-1.

3. If a=a, add current pair to count by incrementing its value by 1.

4. Return the value of count variable.

Implementation for Number of Good Pairs Leetcode Solution

C++ Program

#include

using namespace std;

 

int numIdenticalPairs(vector& nums)

{

int res = 0;

for(int i=0;i

 

www.tutorialcup.com/leetcode-solutions/number-of-good-pai...

Problem Statement

In this problem a string is given and we have to reverse only the vowels of this string.

Example

"hello"

"holle"

Explanation:

before reversing : "hello"

after reversing : "holle"

"leetcode"

"leotcede"

Explanation:

 

Approach 1 (Using Stack)

We just have to reverse the vowels present in input string. So we can store all the vowels in a stack in the same order from left to right. Then again we can traverse the string and for each vowel character from left to right we will replace it with the topmost value of the stack.

Algorithm

 

- Store all the vowel characters in a set.

- Create a stack and push all vowel characters present in the input string from left to right.

- Now again traverse the string for each character. If current character is vowel, replace it with the topmost character of the stack (rightmost vowel character of input string) and remove it from the stack.

- Return the converted string.

 

Implementation for Reverse Vowels of a String Leetcode Solution

C++ Program

#include

using namespace std;

 

string reverseVowels(string s) {

 

set vowels={'a','e','i','o','u','A','E','I','O','U'};

stack stack;

for(char c:s)

{

if(vowels.count(c)) stack.push(c);

}

 

for(char& c:s)

{

if(vowels.count(c))

{

c=stack.top();

stack.pop();

}

}

 

return s;

}

 

int main()

{

string s="leetcode";

cout

 

www.tutorialcup.com/leetcode-solutions/reverse-vowels-of-...

Problem Statement

In this problem we have been given Row index(i) of the Pascal Triangle. We have to create a linear array containing the values of the ith row and return it. Row index starts from 0.

We know that Pascal's triangle is a triangle where each number is the sum of the two numbers directly above it.

 

Example

rowIndex = 3

 

rowIndex = 0

 

As we know that each value in pascal's triangle is a binomial coefficient (nCr) where n is the row and r is the column index of that value.

 

We have discussed similar problem where we have to return all the rows from row index 0 to given row index of pascal's triangle here - Pascal Triangle Leetcode

 

But in this problem we only have to return single row whose index is given.

Here we will discuss three approaches for solution of this problem :

 

- Brute force

- Dynamic Programming

- Maths

 

Approach 1 (Brute Force Recursion)

We know that each number in this triangle is the sum of the two numbers directly above it. i.e

Num(row,col)= Num(row-1,col) + Num(row-1,col-1).

So we can repeatedly call the function Num(rowIndex,j) for each column index of that row, and return the formed list.

 

As we can see we have formulated recursive approach for finding Num(i,j). Now there are some base cases for that which are:

 

- Value at first row will be 1. So for row=0, Num(row, ... ) =0.

- Value at first column will be 1. So for col=0, Num( ... , col)=0.

- Last value of each row will be equal to 1. So for col=row=k, Num(k,k)=0.

 

www.tutorialcup.com/leetcode-solutions/pascals-triangle-i...

The problem Find Winner on a Tic Tac Toe Game Leetcode Solution asks us to find out the winner of a tic tac toe game. The problem provides us with an array or vector of moves made by the players. We need to go through the moves and judge who wins the game. The outcome of the game can be won, draw, or pending. In cases, when any one of them wins the game, we return A or B. But before judging the game, we must be aware of the rules of this specific version of Tic Tac Toe.

 

- Players can only make moves on squares that have not been utilized already.

- The first player A always places "X" characters, while the second player B always places "O" characters.

- "X" and "O" characters are always placed into empty squares. One should never use squares that have already been utilized.

- The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.

- The game also ends if all squares are non-empty. In some cases, both of them do not win and end up in a draw.

- No more moves can be played if the game is over. If there are some moves left, the verdict is "Pending".

- Player "A" makes the first move and then alternate turns are used by both the players.

 

Let's take a look at a few examples.

moves = ,,,,]

"A"

 

Explanation: As shown above in the figure, the player with the "X" wins the game. A always starts the game, thus the winner is also "A".

Approach

 

www.tutorialcup.com/leetcode-solutions/find-winner-on-a-t...

Problem Statement

In this problem, we are given an array. For each element of this array, we have to find out the number of elements smaller than that element.

i.e. for each i (0

 

www.tutorialcup.com/leetcode-solutions/how-many-numbers-a...

Problem Statement

In this problem we are given an array of integers and we have to check if there exists any duplicate element which are at a distance of at least k to each other.

i.e. the difference between the indices of those two same element should be less than equal to k.

Or, nums==nums and abs(i-j)

 

www.tutorialcup.com/leetcode-solutions/contains-duplicate...

The problem Minimum Time Visiting All Points Leetcode Solution provides us with an array or vector of points on coordinate axes. The problem after providing us with the input asks us to find the minimum time to visit all the points given in the input. When you move one unit in either of the x or y direction, you take 1 unit of time. When you move diagonally that is move 1 unit in both directions simultaneously. You encounter 1 unit time. Now, find out the minimum time required to visit all the given points. There is another condition. The condition states that we are required to travel all the points in the same order as given in input. So, without moving directly to the solution, let us take a look at some examples.

 

,,]

7

Explanation: As also shown in the image, we need 3 unit time to move from first point to second. Then 4 unit time to move from second to last point. Thus, a total of 7 units of time is required.

Approach for Minimum Time Visiting All Points Leetcode Solution

The problem Minimum Time Visiting All Points Leetcode Solution asks us what is the minimum time to visit all the points given in the input. The problem also bounds us to travel the points in the same order as they are provided in the input. We are also told about the cost of each move. We can either move 1 unit in either of the two directions or we can move simultaneously 1 unit in both of the directions. All of these moves cost us 1 unit of time.

 

www.tutorialcup.com/leetcode-solutions/minimum-time-visit...

2