View allAll Photos Tagged interviewprep

India has amongst the lowest female labor force participation rates in the world. Less than a third of women – 15 years or older – are working or actively looking for a job.

 

This story is about a girl named Seema. She belongs from Mayurbhanj district and is the first girl to come out from her village to live her dreams. Amid by the cultural, social and parental barriers, she fought with everyone to achieve success and currently working in FIEM – Bhiwandi district (Rajasthan).She has been financially supporting her family and guiding other girls, who now got the strength to see dreams like her. She has become a role model for her village, where she is challenging and creating a change in this stereotype male dominant society.

 

For more details watch complete video....

 

For more details please visit at: lnkd.in/eHb7yEr

 

Facebook: lnkd.in/eXVUiPW

 

Linked in: lnkd.in/eNeee_2

 

#supplychain #logistics #supplychainmanagement #jobs #jobhunt #jobseeker #career #careerplacements #careerguide #training #skilling #Seema

 

#Interview #JobInterview #InterviewTips #InterviewPrep #InterviewAdvice

 

#supplychain #logistics #training #skilling #job #career #HappyNewYear2020 #careerdevelopment

 

#resumetips #jobs #career #JobHaiToRaubHai

 

#StepUpYourGame #GetSafeducated #CareerTips #Resume #CV #CurriculumVitae #JobHunting #InterviewPrep #Interview #VideoResume #NewResume #JobSeeker #CareerOpportunities

 

#Top10HighestPayingJobs #TopHighestpaidJobs #Top10Technologies #JobHaiToRaubHai #Safejob #Safeducate #Safexpress #Interview #Career #CareerDevelopment #Training #JobsInIndia #India #Delhi #Naukri #ShineJob #MonsterJob #NRC #Indore #Raipur #Lucknow

 

#Career #Jobs #Industry #Skills #InterviewTalk #Guidance #CareerGuide #Jobseeker #jobseekers #careerassessment #careerinsight #softskills #jobhunting #supplychain #leadershipskills #teamskills

#skill #training #corporatetraining #skilldevelopment #skillindia #career #skilling #skilled #getskilled #skillsforcareer #logistics #supplychainmanagement #careergoals #careeradvice #jobtips #careertips #careerdevelopment #AsliFans #JohnCena #BB13OnVoot

 

#upskilling #leaders #leadersoftomorrow #mondayqoutes #training #learning #logistics #supplychain #supplychainmanagemen #Logistics #SupplyChain #3D #3DPrinting #Technology #Innovation #Digitalization #Trends #TechnologyTrends

 

#Upskilling #Skills #Skilling #Leadership #Motivation #Planning #Creativity #Career #JobSkills

#Ramagya

#NewYears2019 #MakeASafeResolution #NewYearResolutions #RajasthanRoyals #PrachiMishra #NewBeginnings #NewOpportunities #NewInnovations #NewResolutions #Top10HighestPayingJobs #TopHighestpaidITJobs #Top10Technologies #JobHaiToRaubHai #Safejob #Safeducate #Safexpress #Interview #Career #CareerDevelopment #Training #JobsInIndia #India

Day 304 of 365 (Year Two)

 

Tomorrow morning is the big day. Interview time. I've got my paper work together and my suit is our of the closet and ready. Hopefully everything will go well tomorrow and there will be an offer following the interview.

 

Being home has been nice, but I'm ready to be working again. Being unemployed has put a bit of a damper on the holiday festivities as well. We are still going trick or treating with friends of Savanah's, but no pumpkins this year. I love carving pumpkins, but it just wasn't in the budget this year. Oh well, there is always next year.

 

Most of my focus this week has been on the interview and looking for other opportunities just in case. Like they say, don't put all your eggs in one basket.

Problem Statement

We are given an array of integers. We need to return the integer which occurs more than ⌊N / 2⌋ time in the array where ⌊ ⌋ is the floor operator. This element is called the majority element. Note that the input array always contains a majority element.

Example

Array = {1 , 3 , 3 , 3}

3

Exaplanation: ⌊N / 2⌋ = 4 / 2 = 2. And the integer '3' occurs 3 times in the array.

Array = {1 , 1 , 2}

1

Explanation: ⌊N / 2⌋ = ⌊3 / 2⌋ = 1. And '1' occurs 2 times in the array.

Approach(Hashtable)

We can store the frequency of every element in the array in a hash table. It then becomes easy to check for an integer having frequency > ⌊N / 2⌋.

Algorithm

 

- Initialize a hash table to store the frequency of integers in the array: frequency

- For every element, i, in the array:

 

- Increment frequency or set frequency = 0 if it is not in the table already

- If frequency > N / 2:

 

- return i

 

- Return -1 (to avoid compilation error)

- Print the result

 

Implementation of Majority Element Leetcode Solution

C++ Program

#include

using namespace std;

 

int majorityElement(vector &a)

{

int majorityCount = ((int) a.size()) / 2;

unordered_map frequency;

for(int &i : a)

{

if(++frequency > majorityCount)

return i;

}

return -1;

}

 

int main()

{

vector a = {1 , 1 , 2 , 2 , 1 , 2 , 2};

cout

 

www.tutorialcup.com/leetcode-solutions/majority-element-l...

Watch the incredible stories of Pankaj Kumar and Mritunjay Kumar Sharma who dared to dream big and overcome their disabilities to chart a new course in their life setting an inspiring example to follow. Find out how these unbreakable, who refused to simply lie and succumb to their extremely adverse circumstances. They both have a real and powerful purpose in life.

 

For more details watch complete video....

 

To know more about Safejob, please visit at : safejob.in

  

#supplychain #logistics #supplychainmanagement #jobs #jobhunt #jobseeker #career #careerplacements #careerguide #training #skilling

#Safejob #Safeducate #jobhaitoraubhai #career #jobsearch #jobinterview #interview #microsoft #billgates #recruitment #India #Instagram #news #jobvacancies #Safexpress

 

#Interview #JobInterview #InterviewTips #InterviewPrep #InterviewAdvice

 

#supplychain #logistics #training #skilling #job #career #HappyNewYear2020 #careerdevelopment #businessworld

 

#resumetips #jobs #career #JobHaiToRaubHai

 

#StepUpYourGame #GetSafeducated #CareerTips #Resume #CV #CurriculumVitae #JobHunting #InterviewPrep #Interview #VideoResume #NewResume #JobSeeker #CareerOpportunities

 

#Top10HighestPayingJobs #TopHighestpaidJobs #Top10Technologies #JobHaiToRaubHai #Safejob #Safeducate #Safexpress #Interview #Career #CareerDevelopment #Training #JobsInIndia #India #Delhi #Naukri #ShineJob #MonsterJob #NRC #Indore #Raipur #Lucknow

 

#Career #Jobs #Industry #Skills #InterviewTalk #Guidance #CareerGuide #Jobseeker #jobseekers #careerassessment #careerinsight #softskills #jobhunting #supplychain #leadershipskills #teamskills

#skill #training #corporatetraining #skilldevelopment #skillindia #career #skilling #skilled #getskilled #skillsforcareer#logistics #supplychainmanagement #careergoals #careeradvice #jobtips #careertips #careerdevelopment

 

#upskilling #leaders #leadersoftomorrow #mondayqoutes #training #learning #logistics #supplychain #supplychainmanagemen #Logistics #SupplyChain #3D #3DPrinting #Technology #Innovation #Digitalization #Trends #TechnologyTrends

 

#Upskilling #Skills #Skilling #Leadership #Motivation #Planning #Creativity #Career #JobSkills

 

#NewYears2019 #MakeASafeResolution #NewYearResolutions #NewBeginnings #NewOpportunities #NewInnovations #NewResolutions #Top10HighestPayingJobs #TopHighestpaidITJobs #Top10Technologies #JobHaiToRaubHai #Safejob #Safeducate #Safexpress #Interview #Career #CareerDevelopment #Training #JobsInIndia #India #PetrolPrice #JusticeForKajal

 

#SupplyChain #Logistics #Healthcare #Pharmaceutical #CareerGuide #CareerGoals #Jobs #JobSeekersM

 

#Top10HighestPayingJobs #TopHighestpaidJobs #Top10Technologies #JobHaiToRaubHai #Safejob #Safeducate #Safexpress #Interview #Career #CareerDevelopment #Training #JobsInIndia #India #Lucknow #Raipur #Delhi #Jaipur #NRC

 

#MakarSankranti #harvest #harvestfestival #festival #logistics #supplychain

 

#Safejob #Safeducate #jobhaitoraubhai #career #jobsearch #jobinterview #interview #InterviewTips #Instagram #safexpress #naukri #training #school

 

#safejob #safeducate #careercoach #jobs #jobhaitoraubhai #jobvacancies #newstart #shriramswaroopmorialuniversity #integraluniversity #amityuniversity #delhi #lucknowuniversity #student #raipur #jaipur #indian #naukri #collage #university #Training

 

#resumetips #jobs #career

#StepUpYourGame #GetSafeducated #CareerTips #Resume #CV #CurriculumVitae #JobHunting #InterviewPrep #Interview #VideoResume #NewResume #JobSeeker #CareerOpportunities

 

#Top10HighestPayingJobs #TopHighestpaidJobs #Top10Technologies #JobHaiToRaubHai #Safejob #Safeducate #Safexpress #Interview #Career #CareerDevelopment #Training #JobsInIndia #India #Delhi #Naukri #ShineJob #MonsterJob #NRC #Indore #Raipur #Lucknow #Lucknow

 

#Top10HighestPayingJobs #TopHighestpaidJobs #Top10Technologies #JobHaiToRaubHai #Safejob #Safeducate #Safexpress #Interview #Career #CareerDevelopment #Training #JobsInIndia #India #Lucknow #Raipur #Delhi #Jaipur #NRC See less

The problem Unique Paths Leetcode Solution states that you are given two integers representing the size of a grid. Using the size of the grid, the length, and breadth of the grid. We need to find the number of unique paths from the top left corner of the grid to the bottom right corner. There is one another constraint on the direction of movement, at any point of time, one can move only in either down or right direction.

Example

row: 2, column: 2

2

Explanation: There are only two ways possible to complete the task. First either you move to the right or down. If you moved right you can move only down. If you had moved down, then you can move only in the down direction. So, only 2 ways are possible.

 

row: 2, column: 3

3

Explanation: There are 6 ways to reach destination. Consider if you moved to the right, then the problem has been reduced to the above example and you have 2 ways to reach the bottom right corner. If you would have down, then you have only a single way to reach the bottom right corner. Thus, the total number of ways to reach the end is 3.

Brute Force Approach for Unique Paths Leetcode Solution

The problem Unique Paths Leetcode Solution can be solved recursively. Just as we did in the second example, where we reduced the given problem into 2 subproblems. The same thing is what we will do in this solution. Once, we move to the right, then the problem is reduced to subproblem (row, column-1).

 

www.tutorialcup.com/leetcode-solutions/unique-paths-leetc...

In the problem "Palindrome Linked List", we have to check whether a given singly integer linked list is a palindrome or not.

Example

List = {1 -> 2 -> 3 -> 2 -> 1}

true

Explanation #1: The list is palindrome as all elements from the start and back are the same in value.

List = {1 -> 2 -> 3 -> 4 -> 5}

false

Explanation #2: The list is not palindrome as elements from back and forth are not the same.

Approach(Recursion)

This is easy to notice that we need to have the details of the nodes from the back of the array for checking palindrome properties. In this case, we have a singly linked list meaning that we can only iterate forward to reach any node. Thus, it becomes important to use some data structure to hold the nodes from the back, e.g. stack is a possible option as it keeps the most recent node at the top. We can also use recursion similarly. Recursion is an elegant to get the node values in reverse order. Consider the below general pseudocode for better understanding:

inorderTraversal(root)

{

if(root == null)

return;

inorderTraversal(root.left);

print(root.data);

inorderTraversal(root.right);

}

The above code first prints left nodes in the tree because we recursively call the function to go to left children of any root before printing the value of the node itself. Similarly, we can use recursion to go to the last nodes first and when the function will backtrack, we will be getting the node values in reverse order.

 

www.tutorialcup.com/leetcode-solutions/palindrome-linked-...

Watch the incredible story of the young unbreakable Jatin Kumar. The training by Safejob empowered his to believe in herself and gave wings to her career dreams. The interview preparation training and mock interviews gave the confidence to Jatin to chart a new course in his life Jatin Kumar testimonial.

 

Know more watch full video.....

 

To know more about Safejob, please visit at: www.safejob.in

 

#supplychain #logistics #supplychainmanagement #jobs #jobhunt #jobseeker #career #careerplacements #careerguide #training #skilling

 

#Interview #JobInterview #InterviewTips #InterviewPrep #InterviewAdvice

 

#supplychain #logistics #training #skilling #job #career #careerdevelopment #businessworld

 

#resumetips #jobs #career #JobHaiToRaubHai

 

#StepUpYourGame #GetSafeducated #CareerTips #Resume #CV #CurriculumVitae #JobHunting #InterviewPrep #Interview #VideoResume #NewResume #JobSeeker #CareerOpportunities

 

#Top10HighestPayingJobs #TopHighestpaidJobs #Top10Technologies #JobHaiToRaubHai #Safejob #Safeducate #Safexpress #Interview #Career #CareerDevelopment #Training #JobsInIndia #India #Delhi #Naukri #ShineJob #MonsterJob #NRC #Indore #Raipur #Lucknow

  

Watch Safeducate CEO Ms. Divya Jain's interview in CNBC Awaaz, where she discusses the fact that the social sector doesn't need to be a NGO. Let's redefine some norms, let's skill India!

 

Register today at Safejob Community to get free expert advice for all your career related queries.

 

Join now : safejob.in/

  

#Interview #JobInterview #InterviewTips #InterviewPrep #InterviewAdvice

 

#supplychain #logistics #training #skilling #job #career #careerdevelopment

 

#resumetips #jobs #career #JobHaiToRaubHai

 

#StepUpYourGame #GetSafeducated #CareerTip #Resume #CV #CurriculumVitae #JobHunting #InterviewPrep #Interview #VideoResume #NewResume #JobSeeker #CareerOpportunities#Career #Jobs #Industry #Skills #InterviewTalk #Guidance #CareerGuide #Jobseeker #jobseekers #careerassessment #careerinsight #softskills #jobhunting #supplychain #leadershipskills #teamskills

#skill #training #corporatetraining #skilldevelopment #skillindia #career #skilling #skilled #getskilled #skillsforcareer #logistics #supplychainmanagement #careergoals #careeradvice #jobtips #careertips #careerdevelopment

 

#upskilling #leaders #leadersoftomorrow #training #learning #logistics #supplychain #supplychainmanagemen #Logistics #SupplyChain #Technology #Innovation #Digitalization #Trends #TechnologyTrends

 

#safejob #safeducate #jobhaitoraubhai #CNBC #news #skillindia #career #job #naukri #interview #interviewtips

Ms. Shweta Goela, AGM Safexpress, speaks about why you should choose Logistics as a career and what the sector offers for young logistics aspirants in this week's #SafeducateTalks.

 

For more details watch complete video....

 

#supplychain #logistics #training #skilling #job #career #careerdevelopment

#resumetips #jobs #career

#StepUpYourGame #GetSafeducated #CareerTips #Resume #CV #CurriculumVitae #JobHunting #InterviewPrep #Interview #VideoResume #NewResume #JobSeeker #CareerOpportunities

#Top10HighestPayingJobs #TopHighestpaidJobs #Top10Technologies #JobHaiToRaubHai #Safejob #Safeducate #Safexpress #Interview #Career #CareerDevelopment #Training #JobsInIndia #India #Naukri

 

For more details please visit at: www.safejob.in

  

When you fill out the application, this is the first impression that the employer will have of you - so make sure it's a good one. Come prepared with a resume and references. Fill out the application completely and thoroughly - beware of spelling and grammatical errors.

Master your Skills with our dedicated Customized Corporate Training Programme which will help young enthusiasts to achieve their true potential, boost their productivity and efficiency in the corporate segment. Get Safeducated today!

 

Watch complete video to Know More

 

For more details please visit at:

 

www.safejob.in

 

#supplychain #logistics #supplychainmanagement #jobs #jobhunt #jobseeker #career #careerplacements #careerguide #training #skilling

 

#Interview #JobInterview #InterviewTips #InterviewPrep #InterviewAdvice

 

#supplychain #logistics #training #skilling #job #career #careerdevelopment

 

#resumetips #jobs #career #jobhaitohraubhai

 

#StepUpYourGame #GetSafeducated #CareerTips #Resume #CV #CurriculumVitae #JobHunting #InterviewPrep #Interview #VideoResume #NewResume #JobSeeker #CareerOpportunities

  

Do this to dramatically improve your hit rate at interviews.

interview prep at a bus stop: going over notes, listening to lady gaga, changing into heels, hydrating.

The problem Permutations Leetcode Solution provides a simple sequence of integers and asks us to return a complete vector or array of all the permutations of the given sequence. So, before going into solving the problem. We should be familiar with permutations. So, a permutation is nothing but an arrangement of given integers. So, when we say that we need all the permutations of a sequence. We mean that we are required to print or return all possible arrangements of the given sequence. Let's take a look at a few examples for better understanding.

Given sequence:

Permutations: ,,,,,]

 

Explanation: All the ways that you can write 1, 2, 3 in a sequence have been given as output. There are a total of 6 ways to write 1, 2, 3 in a permutation.

 

,]

Explanation: There are only 2 ways possible to write 0, 1.

Backtracking Approach for Permutations Leetcode Solution

 

The problem Permutations Leetcode Solution asked us to generate all the permutations of the given sequence. Generally, we are required to generate a permutation or some sequence recursion is the key to go. But here the recursion or backtracking is a bit tricky. One way could have been picking an element from unpicked elements and placing it at the end of the answer. This way generate a permutation and somehow make sure to remember that this permutation has been generated and should not be repeated. But instead of doing this, we try to find a simple way to perform the task.

 

www.tutorialcup.com/leetcode-solutions/permutations-leetc...

Problem Statement

In this problem, we are given an array of integers. It contains elements ranging from 1 to N, where N = size of the array. However, there are some elements that have disappeared and some duplicates are present in their place. Our goal is to return an array of all such disappeared integers.

Example

Array = {1 , 2 , 5 , 6 , 2 , 5}

3 4

 

Array = {1 , 2 , 3 , 4}

n

 

Approach(Using HashSet)

We can mark every element in the array and then loop in the range: to check which elements have disappeared or are missing in the array. We use a hash set to store whether an integer has been marked or not.

Algorithm

 

- Initialize a hash set mark to store elements that are present.

- For every element i in the array:

 

- Add i to mark

 

- Initialize a List/vector result to store missing elements in the array

- For every element i in the range: :

 

- If i is not present in mark:

 

- Add it to result

 

- Return result

- Print the result

 

Implementation of Find All Numbers Disappeared in an Array Leetcode Solution

C++ Program

#include

using namespace std;

 

vector findDisappearedNumbers(vector &a)

{

unordered_set mark;

for(int &i : a)

mark.insert(i);

int N = a.size();

vector result;

for(int i = 1 ; i

 

www.tutorialcup.com/leetcode-solutions/find-all-numbers-d...

Problem Statement

In this problem, we are keep tracking of our position in a folder system. We are initially at the root folder or the main folder of this system.

We have basically 3 kind of commands here. The commands are in the form of string in which each string means a command.

 

- "../" means go to the parent folder of the current folder (if already in the root folder then don't go anywhere).

- "./" stay in the current folder.

- "x/" go into the child folder of the current folder which has name x.

 

We are given a sequence of commands which is a combination of above 3 commands. We have to find out the minimum number of operation to go back to the root folder after preforming the given commands.

e.g.

logs =

 

We are at the depth 2 from the root folder. Hence, our answer will be 2.

Example

logs =

2

Explanation:

 

Use this change folder operation "../" 2 times and go back to the main folder.

logs =

3

Approach 1 (Using Stack)

We can use a stack of file names. Initially our stack is empty. Whenever we have to move to a subfolder then the name of the subfolder is pushed into the stack. Thus, the folder in which we are currently present will always remain on the top of the stack.

So, whenever we encounter "../", means we have to come out of the current folder (i.e. move to parent folder), then we will check if the current folder is root. If no, then we will pop the top element from stack.

And of course whenever we will encounter a "./",

 

www.tutorialcup.com/leetcode-solutions/crawler-log-folder...

The problem Destination City Leetcode Solution provides us with some relations between cities. The input is given as line separated pair of cities. Each line in input denotes a direct road from the starting point to the endpoint. It is given in the problem, that the cities do not form a circular route. It is also stated that the input has a destination city. A destination city is defined as a city that does not have any outgoing road. So as usual before diving deep into the solution, let's take a look at a few examples.

 

paths = ,,]

Sao Paulo

Explanation: So if we go by the input, London has a direct road to New York. New York has a direct road to Lima. In the end, Lima has a direct road to Sao Paulo. So, the destination city must be Sao Paulo because it has no outgoing roads.

paths = ]

Z

Explanation: We have a single direct road starting from A to Z. Thus Z is our destination city.

Approach to Destination City Leetcode Solution

The problem Destination City Leetcode Solution asked us to find the destination. The input has provided us with some direct roads among the cities. It is given that a destination city does not have an outgoing road. The problem can be easily solved using a hashmap. In the hashmap, we keep track of outgoing roads. We traverse the paths vector and increment the number of outgoing roads of the cities. Then afterward we check if there is any city among the paths vector, that does not have an outgoing road. We return that city as the answer.

Code

 

www.tutorialcup.com/leetcode-solutions/destination-city-l...

Problem Statement

In this problem, we are given an alphanumeric string i.e. the string has only lowercase alphabets (a-z) and digits(0-9). We are required to return any permutation of this string, in which there is no consecutive alphabet in it or no consecutive digits. If no such permutation is there, then we have to return an empty string.

Example

s = "a0b1c2"

"0a1b2c"

Explanation:

 

No two adjacent characters have the same type in "0a1b2c".

"a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.

s = "leetcode"

""

Explanation:

 

"leetcode" has only characters so we cannot separate them by digits.

Approach

Let's first understand the condition in which we can return a permutation.

Suppose if string is "abcde" then we can't make any possible permutation from it in which no two alphabets or numbers are consecutive.

Similarly if string is "12335" then also we can't do anything.

So, to make alternative alphanumeric string, should we have equal number of digits and alphabets?

No, Let's see example "covid2019" we have 5 alphabets and 4 digits.

Still we have possible ans e.g. "c2o0v1i9d".

 

Now if there would be one more alphabet in the same string, let "covids2019" then also we could not form any possible output.

Thus here we have got a condition that difference of count of alphabets and count of digits should not exceed 1.

i.e. abs(count(digits)-count(alphabets))

 

www.tutorialcup.com/leetcode-solutions/reformat-the-strin...

In this problem, we are given an N-ary tree, that is, a tree that allows nodes to have more than 2 children. We need to find the depth of a leaf farthest from the root of the tree. This is called maximum depth. Note that the depth of a path is the number of nodes on it.

Example

2

 

/ |

 

3 4 6

   

9

3

Explanation: The leaf with value 9 is farthest from the root and its depth is 3. So, we print 3.

2

 

/

 

3 6

 

/ |

 

4 7 9

3

Explanation: The leaves with value 4,7 and 9 are farthest from the root and their depth is 3. So, we print 3.

Approach(Recursive)

The maximum depth of a binary tree is calculated by calling the recursive function on left and right children of any node. Similarly, in case of an N-ary tree, we can calculate the maximum depth by calling the recursive function on all the children of any node. This approach is recursive and requires only a single pass of the tree.

 

Algorithm

 

- Create a function maxDepth() to return the maximum depth of a tree whose root is passed to it

- If root is null:

 

- return 0

 

- Initialize a variable maximumDepth to store the maximum depth of N-ary tree

- For every child in the children list of the current root:

 

- set maximumDepth = max(maxDepth(root.left) , maxDepth(root.right))

 

- return maximumDepth + 1

 

Implementation of Maximum Depth of N-ary Tree Leetcode Solution

C++ Program

#includ

 

www.tutorialcup.com/leetcode-solutions/maximum-depth-of-n...

The problem Remove Palindromic Subsequences Leetcode Solution states that you are given a string. The string consists of only two characters 'a' or 'b'. You are required to erase the whole string. There is a restriction that you can delete only a palindromic subsequence in one move. Find the minimum number of steps required to erase the whole string. Let us take a look at a few examples before jumping into the solution.

 

s = "ababa"

1

Explanation: Since the string is a palindrome. We can remove the whole string in a single move. Thus the answer is also 1.

s = "abb"

2

Explanation: In the first move, we remove "bb". In the second move, we remove "a". Thus we require at least 2 moves to erase the whole string.

Approach for Remove Palindromic Subsequences Leetcode Solution

The problem Remove Palindromic Subsequences Leetcode Solution is an observation one. It requires us to observe that the string consists of only two characters 'a' and 'b'. If we come across a palindrome, we simply return 1. Because it requires a single move to erase a whole palindrome. If we get an empty string, we should return 0. But other than these, there is only a single case, when we have a string that is not palindrome as a whole.

 

But since the string has only 'a' and 'b'. We will take at most 2 moves to remove all the characters. In the first move, we should remove all 'a's. In the second move, we remove all 'b's. Thus the answer to this p !=

 

www.tutorialcup.com/leetcode-solutions/remove-palindromic...

Problem statement

In the problem "Find the Difference" we are given two strings s and t. String t is produced by randomly stuffing the characters of string s and adding one character at a random position.

 

our task is to find out the character which was added in string t.

Example

s = "abcd", t = "abcde"

e

Explanation:

 

After rearranging the characters of string t it becomes "abcde". As "abcd" is already present in string s, so the character that was added to t is "e".

Sorting Approach for Find the Difference Leetcode Solution

If we change our perspective to see the problem then sometimes it becomes easy to solve it. like here the problem says string t is generated by shuffling string s and adding one element at a random position. So, we can see this as string t is generated by adding a character at a random position in the string s. Now we only need to find out the position where the character of string s is not matching with the character of the string t and then we can return the character present at that position. So we will follow these steps:

 

- Sort both the string.

- Check character by character both the string and the point where they didn't match is the added character and that is the answer.

- If all characters matched then the character at the last position of string t is our answer.

 

Implementation

C++ code for Find the Difference

#include

using namespace std;

char findTheDifference(string s, string t) {

sort(s.begin(),s.

 

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

The problem Largest Substring Between Two Equal Characters Leetcode Solution, asks us to find the length of the largest substring. Here, a condition is imposed on the substring. The substring should be between the same characters. So, the string must contain at least two equal characters so that the output happens to be a natural number else -1 is returned. But before moving ahead with the solution let us take a look at a few examples.

 

s = "aa"

0

Explanation: The input contains two 'a's and the string between them happens to be the longest substring satisfying the imposed conditions. Thus, the output is correct.

s = "abca"

2

Explanation: There exists only a single character having at least two instances in the input string. So, the optimal output will contain "bc".

Approach for Largest Substring Between Two Equal Characters Leetcode Solution

The solution for the problem Largest Substring Between Two Equal Characters Leetcode Solution is easy to understand. In the problem, we are only asked to find the length of the largest substring but not the string itself. So, we simply create two arrays that store the first and last index of any character. Initially, we fill these arrays with -1 which denotes no occurrence of a character. Once we find a character we store the index in the first array if it is filled with -1. If that does not have -1, we store the index in the second array.

 

Using these two arrays, we find the maximum length.

 

www.tutorialcup.com/leetcode-solutions/largest-substring-...

The Lucky Numbers in a Matrix Leetcode Solution problem asked us to find a lucky integer from the given matrix. A lucky integer is defined as a number that is the minimum among all other elements in its row and maximum among its column. So there may be more than one lucky integer in the given matrix. So we have the liberty of any one of them. In case there is no lucky number in the matrix, we need to return an empty vector. So before diving deep into the solution, let us have a look at a few examples.

 

matrix = ,,]

 

Explanation: 15 is the minimum number in its row, and also the maximum element in its column. Thus 15 is being returned as output.

Approach to Lucky Numbers in a Matrix Leetcode Solution

The problem Lucky Numbers in a Matrix Leetcode Solution is one of the standard ones. And is asked very often in many coding rounds. The problem is simple since we simply need to check if there exists any element that is minimum in its row. And at the same time it should be maximum in its column. So, we can easily do this, by using two temporary arrays. These arrays store the minimum element of each row and the maximum element of each column.

 

After that, we need to check if there exists some element that is common in both these temporary arrays. So, we can use HashSet where we insert the elements of one array. Then we traverse over the elements of the second array and check if it is present in the HashSet. If some element is present in both the arrays we return that as output.

 

www.tutorialcup.com/leetcode-solutions/lucky-numbers-in-a...

The problem Find N Unique Integers Sum up to Zero Leetcode Solution, provides us with an integer. It asks us to return n unique integers that sum up to 0. So, the question is pretty simple to understand. So, before diving into the solution. Let us take a look at a few examples.

 

n = 5

 

Explanation: Well, there can be multiple outputs to the problem. But let us take the given output. All the integers in the output are unique. Thus satisfying the imposed condition and the sum of all the given integers is 0. Hence, both the conditions are satisfied.

n = 3

 

Explanation: The output given has all unique integers and their sum is also 0. Thus, the output satisfies all the imposed conditions.

Approach for Find N Unique Integers Sum up to Zero Leetcode Solution

The approach for the problems is most of the times is cracking the pattern. There is always some underlying patterns in these type of questions. So, whenever we try to find the pattern for a question. Always try to find the answer for smaller values of n, then try to find the pattern. For n = 1, output can be 0. For n = 2, output can be . Similarly for n = 3, output can be , for n = 4, output can be . So, we see a pattern that the output forms AP where if the value of n is odd. The middle element is 0. If the value of n is even then the (n+1)/2 element is 1. So, using this information, we can devise a formula. The formula can be a = 2*i+1-n. Now, we simply use this formula to fill the n elements of the array.

Code

 

www.tutorialcup.com/leetcode-solutions/find-n-unique-inte...

The problem "Pow(x, n) Leetcode Solution" states that you are given two numbers, one of which is a floating-point number and another an integer. The integer denotes the exponent and the base is the floating-point number. We are told to find the value after evaluating the exponent over the base. The base can be negative, positive, or zero. The exponent can lie anywhere between the range of an integer. We are also given a constraint on the output. The output will be anywhere between -10000 to +10000. So, let's take a look at a few examples.

 

Example

Base: 2

Exponent: 10

Answer: 1024

Explanation: Since the value for 2^10 = 104, hence the answer. This can also be checked by repetitive multiplication of 2 10 times.

Base: 2

Exponent: -10

Answer: 0.00098

Explanation: The answer has been changed because the value of the exponent has also been changed to -10.

Brute Force Approach

The brute force approach for the problem Pow(x, n) Leetcode Solution is very simple. We need to just simulate the operation of evaluating exponents. An exponent can easily be evaluated by multiplying the base exponent number of times. So, we can easily simulate this using a loop in any of our favorite programming languages. One thing to note, is the corner cases. When either the exponent is equal to the maximum value of integer or minimum value of integer. When we have exponent as the minimum value of integer, the answer can be either 1 or 0.

 

www.tutorialcup.com/leetcode-solutions/powx-n-leetcode-so...

In this problem, we are given two strings. The second string is generated by shuffling the characters of the first string randomly and then adding an extra character at any random position. We need to return the extra character that was added to the second string. The characters will always be lower-case English letters.

Example

a = "abcde" , b = "ebacdf"

f

a = "aaaa" , b = "aaaaa"

a

Explanation #1

 

The extra character that is added to string b is 'f' as string a doesn't contain it.

 

Explanation #2

 

String a has 4 'a' letters while string b has 5. So, the extra letter is 'a'.

Approach(Sorting)

We can sort both the strings and then iterate both of them letter by letter to find the first position where they differ. The second string will always have one extra character. So, we will always find a point where string a and b differs. However, there can be a case where string b after sorting matches every character in string a in but has one extra character in the end. We need to handle this one special case.

 

Algorithm

 

- Sort both the strings, a and b. As it is not possible in java, we first convert them into char arrays

- For every character present in the shorter string, we do a letter-by-letter check:

 

- If the character in string a is not equal to the corresponding character in string b:

 

- return this character.

 

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

Problem Statement

In this problem, we are given an IP Address. We just have to convert it into a Defanged IP Address i.e. in our output string, all the "." are converted to "".

 

Example

#1:

address = "1.1.1.1"

"1111"

#2:

address = "255.100.50.0"

"255100500"

Approach 1 (Using String Stream/Builder)

For this problem we can use simple string stream or builder class to modify the given string.

We can use a string builder (in case of java) and string stream (in case of C++) to convert given string to output string.

We will traverse the input string from left to right. If any character is '.' then, we will append "" in output string. Otherwise we will simply append the character in output string too.

 

Algorithm

 

- Create an empty string stream or builder.

- Run a for loop to traverse each character of given string.

- For each character in string. If character is '." then append "" to string builder. Else append the same character to string builder.

- Convert the stream/builder to string and return it.

 

Implementation for Defanging an IP Address Leetcode Solution

C++ Program

#include

#include

using namespace std;

string defangIPaddr(string address)

{

std::stringstream ss;

 

for(int i=0;i

 

www.tutorialcup.com/leetcode-solutions/defanging-an-ip-ad...

Problem Statement

In this problem, we are given a valid parentheses string (vps) having some numbers, some operators(e.g. +,-,*) and some parentheses(e.g. '(',')').

Valid parentheses strings (vps) are:

 

- ""

- "d" where d is any number

- "(A)" if A is valid parentheses string

- "A*B" if * is any operator and A and B are valid parentheses string.

 

Our aim is to find the maximum depth of the parentheses in the given string.

e.g. "(1+(2*3)+((8)/4))+1"

we can see that at the number 8 is inside the maximum number of parentheses and the depth of parentheses there is 3. We will output 3.

 

Let's see one more example,

e.g. "1+(2*3)/(2-1)"

the vps 2*3 or another vps 2-1, both are inside the maximum depth of parentheses i.e. 1.

Example

s = "(1+(2*3)+((8)/4))+1"

3

Explanation:

 

Digit 8 is inside of 3 nested parentheses in the string.

s = "(1)+((2))+(((3)))"

3

Approach

We are given that the string is a vps and we just have to find out the maximum depth of parentheses. So, we can just focus on the parentheses and ignore other characters (numbers and operators).

 

The depth of parentheses increase only when there starts a new nested parentheses. i.e. the starting parentheses '(' means that depth of parentheses increase by 1. And when the parentheses is closed, then depth decreases by 1. i.e. ')' means depth is decreased by 1.

 

In our approach we will just use a current depth variable (let k) and a maximum depth variable (let ans).Both

 

www.tutorialcup.com/leetcode-solutions/maximum-nesting-de...

Problem Statement

In this problem a binary tree is given with its root. A node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.

 

We have to return the number of good nodes in the given binary tree.

Example

3

/

1 4

/ /

3 1 5

4

Explanation:

 

Nodes in blue are good.

Root Node (3) is always a good node.

Node 4 -> (3,4) is the maximum value in the path starting from the root.

Node 5 -> (3,4,5) is the maximum value in the path

And Node 3 -> (3,1,3) is the maximum value in the path.

3

/

3

/

4 2

3

Explanation:

 

Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.

Approach

To find whether a node is good or not we must traverse path from root to the that node and check if its value is not smaller than maximum in this path.

To find the number of good nodes we have to check like this for each node of the given binary tree. But here observe one thing,

 

if we find the answer for a particular node by traversing its path from root, we can go to its child node also from there itself because we have already traversed almost path of child node also and we also have maximum value traversed till yet. We just have to update the maximum with current node value to transfer to its both children node.

So this looks like a DFS or recursion where to go to a particular node we traverse the path from root to that node. Thus in this problem recursion will be very helpful.

 

www.tutorialcup.com/leetcode-solutions/count-good-nodes-i...

Problem Statement

Given a string, we have to determine if it is a palindrome, considering only alphanumeric characters i.e. numbers and alphabets only. We also have to ignore cases for alphabet characters.

Example

"A man, a plan, a canal: Panama"

true

Explanation:

 

"AmanaplanacanalPanama" is a valid palindrome.

"race a car"

false

Explanation:

 

"raceacar" is not a palindrome.

Naive Approach (Comparing with reverse)

To check if a string is palindrome or not we can simply reverse it and compare it with the original string. After reversing if it remains equal then the given string is a palindrome.

In this problem we have to ignore all the characters except alphabets and numbers. So for that we can filter the given string and save the filtered string in a new variable by removing all unwanted characters. Lets take an example:

         

We can see filtered string and reversed filtered string is not equal, hence it is not a valid palindrome.

Implementation for Valid Palindrome Leetcode Solution

C++ Program

#include

using namespace std;

 

bool isAlphaNum(char c)

{

if( (48

 

www.tutorialcup.com/leetcode-solutions/valid-palindrome-l...

The problem String Matching in an Array Leetcode Solution provides us with an array of strings. The problem asks us to find the strings that are substrings of some other string from the input. Just a quick reminder, a substring is nothing but a part of the string remaining after removing characters from both ends. You can also remove 0 characters from both the ends. And the number of removed characters does not need to be the same. So, for a better understanding let us take a look at a few examples.

 

words =

 

Explanation: The output has "as" because it comes in "mass". Similarly, "hero" is a part of "superhero". Thus, we simply found the substrings of the inputs that are also input.

words =

 

Explanation: This example shows that the substrings can be from the same string. Like here, both the strings in the output are substring of "leetcode".

Approach for String Matching in an Array Leetcode Solution

The problem asked us to pick out the strings from the input that satisfy a specific condition. The condition is that the string should be a substring of a string that is also in the input. So, we try to simulate this process of finding the strings that are substring of some other string. The only complication that remains is the implementation. So, we use hashset or unordered map to keep track of strings that will serve as our output. We use two nested loops that checks if the string at ith index is a substring of string at jth index and vice-versa.

 

www.tutorialcup.com/leetcode-solutions/string-matching-in...

In this problem, we are given the root node of a Binary Search Tree containing integer values and an integer value of a node that we have to add in the Binary Search Tree and return its structure. After inserting the element into the BST, we have to print its Inorder Traversal.

Example

Binary Search Tree:

 

7

 

/

 

3 10

 

/

 

8

Integer Value = 11

3 7 8 10 11

Binary Search Tree:

5

 

/

 

4

 

/

 

3

Integer Value = 2

2 3 4 5

Explanation

 

Approach(Recursive)

In order to decide where should any given node be inserted in our Binary Search Tree, we must set up a path from the root to the corresponding node whose left/right child will be the given node.

 

We can solve this recursively by passing on the task from a problem to its sub-problem. In this case, inserting a new node into a tree means to insert it to either its left subtree or right subtree. The same idea also holds for any further subtrees. We need to set up a base case. When we reach a point where the root node of any subtree is NULL, it would mean that we have reached the end of the path to insert the target node. So, we return a new node address having node value as the given value. Binary Search Trees have a significant advantage to search for any arbitrary element in O(logN) time under average cases. So, in this case, we find the position of the new node to be inserted in efficient time.

Algorithm

 

www.tutorialcup.com/leetcode-solutions/insert-into-a-bina...

Problem Statement

In path crossing problem a_string is given in which there are only four different characters 'N', 'S', 'E' or 'W' showing the movement of an object in one direction at a time by 1 unit. Object is initially at origin (0,0). We have to find out if the object will cross its path at any point walking along the path specified in the given string.

Example

path = "NES"

false

Explanation:

 

Notice that the path doesn't cross any point more than once.

path = "NESWW"

true

Explanation:

 

Notice that the path visits the origin twice.

Approach

From the problem statement it is clear that if a coordinate (x,y) occurs in the path of the object, then it must be the position of the object after certain number of moves as it is moving with 1 unit each time.

So if a point comes in its path which is once previously visited, then it is surely crossing the path. So we can return true as soon as we found this kind of point.

 

Now how do we know that a point has been visited previously. For this we can use a Hash Set and keep storing all the points in its path. At any time if we found that the next point to which object is going is already present in the set, we return true. After completing the path if this doesn't happens, then we return false.

Algorithm :

 

- Create a hash set of keys, where key represents coordinate (x,y). For this we can use pair as key Or we can use a simple string that should represent two integers uniquely.

 

www.tutorialcup.com/leetcode-solutions/path-crossing-leet...

VC Waterfall, Exciting news!! Kirsten Rose has been appointed as the new part time Career Centre Coordinator for The IIE’s Varsity College Waterfall campus.

Her academic background is in Psychology. Dealing with people from all walks of life is her passion. She pride herself in finding a passion between you and your desired field of work. She can assist you in making your qualification work for you. Connect with her today! E-mail: 40255@iieconnect.co.za #vcwfl #vccareercentre #careeradvice #cvhelp #jobapplications #interviewprep

 

In this problem, we are given an array of integers. The goal is to find all the elements which occur more than ⌊N / 3⌋ time in the array where N = size of the array and ⌊ ⌋ is the floor operator. We need to return an array of such elements.

 

Range of elements: -10^9 to 10^9

Example

Array = {1 , 2 , 3 , 3 , 2}

2 3

Explanation: ⌊N / 3⌋ = ⌊5 / 3⌋ = 1. Now, the integers 2 and 3 have frequencies equal to 2, which is greater 1. So, we print them.

Array = {1 , 2 , 3 , 4}

No majority elements

Explanation: We did not find any element whose frequency is greater than 1 in this case. So, we print "No Majority elements".

Approach(Storing Frequencies)

As the title suggests, we can store the frequency of every element in the array using a hash table and then check for elements having a frequency greater than ⌊N / 3⌋. In this way, we can find all elements that satisfy the condition.

Algorithm

 

- Initialize a HashMap-frequency to store the frequencies of elements in the array and a list/vector result to store the majority elements

- For every element i in the array:

 

- Increment its frequency: frequency++(or set as 1 if not present already)

 

- For every key in the hashmap:

 

- If frequency > N / 3

 

- Add it to the result

 

- Return the list result

 

Implementation of Majority Element II Leetcode Solution

C++ Program

#include

using namespace std;

 

vector majorityElement(vector& a)

{

int N = a.size();

 

www.tutorialcup.com/leetcode-solutions/majority-element-i...

Problem Statement

In this problem, we are given a length. We have to generate a string that has all characters an odd number of times. For example, aaaaab is a valid string because count(a)=5 and count(b)=1.

But, aaabbc is not a valid string here because count(b)=2 which is an even number.

Example

n = 4

"pppz"

Explanation:

 

"pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love".

n = 2

"xy"

Explanation:

 

"xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur".

Approach

We can use a trick here.

If the length of string is odd number then we can use a single character throughout to create the string, and if the input length is even number then we can create a string having just two characters.

One character occuring n-1 times (which will be an odd number because n is even here) and anoter character just once (which is ofcourse an odd count).

 

For example n=4, our output will be aaab

and if n=3, our output will be aaa

 

we are just using characters a and b in our solution, there are more options of characters if you want.

Implementation

C++ Program for Generate a String With Characters That Have Odd Counts Leetcode Solution

#include

using namespace std;

 

string generateTheString(int n)

{

string str;

if(n%2==0)

{

for(int i=0;i

 

www.tutorialcup.com/leetcode-solutions/generate-a-string-...

Problem Statement

In this problem we are given a column title as appear in an Excel sheet, we have to return the column number that corresponds to that column title in Excel as shown below.

 

Example

#1

"AB"

28

#2

"ZY"

701

Approach

To find column number for a particular column title we can think of it like converting from one number system to another number system.

Like in decimal number we have characters 0 to 9 to represent any number in decimal. Similarly in column title the characters are from A to Z to represent any number. There are total of 26 symbols for each place, therefore we can think of a number in a system whose base is 26.

 

Now question becomes very simple. Like we convert any binary or hexa-decimal number to its decimal form, we have to convert this title string into a decimal number.

 

For example, if we want to find the decimal value of string "1337", we can iteratively find the number by traversing the string from left to right as follows:

'1' = 1

'13' = (1 x 10) + 3 = 13

'133' = (13 x 10) + 3 = 133

'1337' = (133 x 10) + 7 = 1337

 

Now in this problem as we are dealing with base-26 number system. Based on the same idea, we can just replace 10s with 26s and convert alphabets to numbers.

 

For a title "LEET":

 

L = 12

E = (12 x 26) + 5 = 317

E = (317 x 26) + 5 = 8247

T = (8247 x 26) + 20 = 214442

Implementation

C++ Program for Excel Sheet Column Number Leetcode Solution

#includ

 

www.tutorialcup.com/leetcode-solutions/excel-sheet-column...

The problem To Lower Case Leetcode Solution provides us with a string and asks us to convert all the upper case alphabets into lower case alphabets. We are required to convert all the upper case or lower case alphabets into lower case characters. So, the problem seems simple but before diving into the solution. We take a look at a few examples.

 

"Hello"

"hello"

Explanation: The input has an upper case alphabet 'H' which is converted into the lower-case alphabet 'h'. The other characters "ello" stay the same and we do not need to convert them.

"here"

"here"

Explanation: Since all the alphabets in the input are lower case characters. We do not need to change any of the characters and can return the input without any modification.

Approach using in-built functions

The problem To Lower Case Leetcode Solution asked us to simply convert the upper case character to the lower case character. This operation can be easily done using in-built functions in programming languages. So, we can use tolower() in C++, or toLowerCase() in Java. Using these functions, we only need to pass the given string as input. Then we get the string with all characters in lower case.

Code

C++ code for To Lower Case Leetcode Solution

#include

using namespace std;

 

string toLowerCase(string str) {

transform(str.begin(), str.end(), str.begin(), (unsigned char c){ return std::tolower(c); });

return str;

}

 

int main(){

cout

 

www.tutorialcup.com/leetcode-solutions/to-lower-case-leet...

As the title says, we need to find the square root of a number. Let say the number is x, then Sqrt(x) is a number such that Sqrt(x) * Sqrt(x) = x. If the square root of a number is some decimal value, then we have to return the floor value of the square root.

Example

4

2

7

2

Approach(Pre-built functions)

The math library of C++ and lang.Math library of Java have the pre-built functions to return the square root of a number. We can apply floor() to avoid any decimal value.

Algorithm

 

- If the number is less than 2, return itself

- Call the sqrt() function

- Floor the value obtained

- Print the result

 

Implementation of Sqrt(x) Leetcode Solution

C++ Program

#include

using namespace std;

 

int mySqrt(int x)

{

if(x

 

www.tutorialcup.com/leetcode-solutions/sqrtx-leetcode-sol...

Problem Statement

In Matrix Diagonal Sum problem a square matrix of integers is given. We have to calculate the sum of all the elements present at its diagonals i.e. elements at primary diagonal as well as secondary diagonal. Each element should be counted only once.

Example

mat = ,

,

]

25

Explanation:

 

Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25

Notice that element mat = 5 is counted only once

mat = ,

,

,

]

8

Explanation:

 

Diagonals sum: (1+1+1+1)+(1+1+1+1)=8.

Approach

 

In given square matrix we have to just add the diagonal elements and return its sum.

Lets see what will be the indices pattern in the matrix for diagonal elements. First if we see on the primary diagonal, its first element is on index i=0,j=0 and next element is on (i+1,j+1). Similarly last element will be on index (n-1,n-1) where n is the width of the given square matrix. All indices on this diagonal have i=j.

So we can iterate over this diagonal in a loop as follows:

 

1. Initialise i=0 and j=0.

2. Run a loop while i

 

www.tutorialcup.com/leetcode-solutions/matrix-diagonal-su...

The problem Minimum Absolute Difference Leetcode Solution provides us an unsorted array or vector containing some integers. We are required to find out all the pairs that have a difference equal to that of minimum absolute difference. The minimum absolute difference is the minimum value of absolute difference that can be achieved by picking up any two different elements among all possible integers from the given vector or array. So, without diving deep into the solution let's first take a look at a few examples.

arr =

,,]

 

Explanation: Since there are only three such pairs with the minimum absolute difference. We return them as the answer to the problem. All three of them have the same difference of 1. The difference of 1 is the least possible difference.

arr =

]

Explanation: Since the minimum absolute difference is equal to 2, and can be achieved only by a single pair of integers. This pair of integers is returned as the answer.

Approach for Minimum Absolute Difference Leetcode Solution

The problem Minimum Absolute Difference Leetcode Solution, asks us to find all the pairs of integers that have the difference between them equal to the minimum absolute difference. We had already stated what is the minimum absolute difference. So, instead of looking at that let's focus on how to solve the problem. So, first of all, we need to find the minimum absolute difference.

 

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

In this problem, we have to find a pair of two distinct indices in a sorted array that their values add up to a given target. We can assume that the array has only one pair of integers that add up to the target sum. Note that the array is sorted in a non-decreasing manner.

Example

Array = {1 , 2 , 3 , 4 , 5}

Target = 6

1 5

Array = {1 , 4 , 5 , 11 , 12}

Target = 9

2 3

Approach(Brute Force)

This approach is straightforward. We can check for every pair in the array and if their sum is equal to the given target, print their indices. This kind of Brute Force solution needs to check every possible pair and number of possible pairs in the array = n * (n - 1) / 2. So, in the worst-case, this approach can be slow.

Algorithm

 

- Run a loop to maintain the first index of the solution in the array

- Run another loop to maintain a second index of the solution for every first integer

- If at any point, the sum of values of two indices is equal to the target

 

- Print its indices

 

Implementation of Two Sum Leetcode Solution

C++ Program

#include

using namespace std;

 

vector targetSum(vector &a , int &target)

{

int n = a.size();

for(int i = 0 ; i < n - 1 ; i++)

for(int j = i + 1 ; j < n ; j++)

{

if(a + a == target)

return {i + 1 , j + 1};

}

return {};

}

 

int main()

{

vector a = {1 , 4 , 5 , 11 , 12};

int target = 9;

for(int &x : targetSum(a , target))

cout

 

www.tutorialcup.com/leetcode-solutions/two-sum-leetcode-s...

Problem Statement

In this problem two arrays are given and we have to find out the intersection of this two arrays and return the resultant array.

Each element in the result should appear as many times as it shows in both arrays. The result can be in any order.

Example

nums1 = , nums2 =

 

nums1 = , nums2 =

 

Approach 1 (Using Hash map)

To find out the intersection of two arrays (nums1 and nums2) we can first store the count of each element of one array (let nums1) using a Hash map. Then we can traverse through the second array (nums2) and for each element in nums2 we would check if count of that element in nums1 is positive or not.

 

- if count of nums2 in array nums1 is positive, then add this element(nums2) in result array. And decrease the count of this element in Hash map.

- else this element is not to be added in result.

 

Note: we will store the elements of that array in hash map whose size is smaller so as to minimize the space complexity.

Implementation for Intersection of Two Arrays II Leetcode Solution

C++ Program

 

www.tutorialcup.com/leetcode-solutions/intersection-of-tw...

Problem Statement

In this problem, we are given two non-negative integers low and high. We have to find how many odd numbers are there in the given interval range .

Example

low = 3, high = 7

3

Explanation:

 

The odd numbers between 3 and 7 are .

low = 8, high = 10

1

Explanation:

 

The odd numbers between 8 and 10 are .

Approach

One way to find the total count of odd numbers in the given interval range is to traverse from the left to right boundary of the interval in a loop and increase the odd counter for each odd number. But this will be a very lame approach for counting odd numbers in a range. This will take linear time complexity, and that we don't want for such an easy problem.

 

It is very easy to find total odd numbers in the given interval range as we know there are almost half even and half odd numbers in an interval range.

But we have to consider the interval boundaries very carefully. So what we can do is we can form the formula for the count of odd numbers in first n natural numbers. Let it be count. Then odd numbers between low and high will be equal to :

count = count - count.

 

Now taking some examples for count :

 

count=1

count=1

count=2

count=2

count=3

 

We can deduce that count = (n+1)/2

Hence count = (high+1)/2 - low/2

Implementation

C++ Program (Naive Approach) for Count Odd Numbers in an Interval Range Leetcode Solution

#include

using namespace std;

 

int countOdds(int low, int high)

{

int count=0;

for(int i=low;i

 

www.tutorialcup.com/leetcode-solutions/count-odd-numbers-...

A binary tree is Height-balanced if the difference of heights of left and right subtree of every node in the tree is at most 1. In this problem, we are going to check for a balanced binary tree.

 

Example

2

 

/

 

1

 

/

 

4

Not balanced

1

 

/

 

2 3

Balanced

Approach

It is intuitive to think that, for every node in the binary tree, we can check whether or not the left and right subtrees follow the required condition. That's the "Brute Force" method.

 

But, in order to check whether the tree is balanced, the approach can be improved on grounds of Time & Space complexities.

 

We follow an approach such that we solve the problem in a Bottom-Up manner. Check whether the subtrees of a node are itself, balanced binary trees(or not) and obtain the height of the binary tree at the same time, which can be generalized using recursion.

Algorithm(Brute Force)

 

- Start from the root and keep traversing the binary tree until the root becomes NULL

- Retrieve the height of left and right subtrees using height() function

 

- If the difference is more than '1':

 

- return false. As the tree does not satisfy the balance condition

 

- Check the balance condition for left and right subtrees recursively

 

- Print the result

 

Algorithm(Optimal)

 

- If the tree is empty, we can say it's balanced. If not, we can follow other steps:

- Create a helper function to return the "height" of a current subtree, using recursion.

 

www.tutorialcup.com/leetcode-solutions/balanced-binary-tr...

1 3