0% found this document useful (0 votes)
5 views37 pages

35 Dsa Problems

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views37 pages

35 Dsa Problems

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 37

1.

PALINDROME NUMBER:
------------------

Problem Description:

Given an integer x, return true if x is a palindrome and false otherwise.

Input format
First line contains a single integer x.
Output format
Return boolean value.

Sample Input 1
121
Sample Output 1
true
Explanation
121 reads as 121 from left to right and from right to left.

Sample Input 2
-121
Sample Output 2
false
Explanation
From left to right, it reads -121. From right to left, it becomes 121-.
Therefore it is not a palindrome.

Constraints
-2^31 <= x <= (2^31 - 1)

SOLUTION:
---------
function Palindrome(x){
let n=x;
let rev=0;
let s=0;
while(n>0){
rev=n%10;
s=rev+(s*10);
n=Math.floor(n/10)
}
if(x===s){
return true;
}else{
return false;
}

***********************************************************************************
***********************************************************************************
*****
2.Find If an array contains any duplicates
----------------------------------------

Problem Description:
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the
array, and it should return false if every element is distinct.
Input format:
First-line will contain an integer n denoting the number of numbers in the
list.
Next line will contain n space-separated integers.

Output format
Print "false" if no duplicate found otherwise “true”.

Sample Input 1
4
1 2 3 1

Sample Output 1
true

Sample Input 2
4
1 2 3 4

Sample Output 2
false

Sample Input 3
10
1 1 1 3 3 4 3 2 4 2

Sample Output 3
true

Constraints
0<= n <=1000000
-1e6 <= a[i] <= 1e6

SOLUTION
----------
function containsDuplicateNum(nums){

let set=new Set();


for(let num of nums){
if(set.has(num)){
return true;
}else{
set.add(num);
}
}
return false;

***********************************************************************************
***********************************************************************************
*****
3.Generate Passcode string
--------------------------

Problem Description
Rohan is playing a game in which he has got two strings, string A and
string B. He needs to generate a passcode to qualify for the next
level using those strings. The passcode will be in the form of a string. He
needs to take the first character of string A and he should add it to the
passcode. After that, he needs to take the first character of string B and he
should add it to the passcode. Then he needs to take the second character of
string A and he should add it to the passcode, and so on.He needs to continue
the process until there are no letters left in one of either A or B. When
this happens, add all the remaining letters of the other string to the
passcode. This is the resultant passcode to qualify for the next level, return
this.

Input format
First line contains string A.
Second line contains string B

Output format
Return a string(passcode).

Sample Input 1
aaaaa
bbb

Sample Output 1
abababaa

Explanation
First character is A[0] which is a.
Second character is B[0] which is b. Second character is A[1] which is
a.
and so on...

Constraints
1<=A.length<=100000
1<=B.length<=100000
SOLUTION
---------

function passcode(A,B){
let n=Math.min(A.length,B.length);
let i=0;
let pass=" ";

while(i>n){
pass += A[i]+B[i];
i++;
}
while(A.length>n){
pass+=A[i];
i++;
}
while(B.length>n){
pass+=B[i];
i++;
}
return pass;

}
----------------------------------------------

***********************************************************************************
***********************************************************************************
*****
4.FIXED POINT

Problem Description
Given a sorted array, find a fixed point - that is, where A[i] = i. If one is
present, return the index i. If none is present, return -1.
You may assume that there’s only one such fixed point and that there are no
duplicates in the array.

NOTE: Indexing starts from 0.

Input format
There are 2 lines of input.
First line will contain the single integer representing N.
Next line will contain N space separated integers representing Array A.

Output format
Print the single integer

Sample Input 1
5
-3 -1 2 4 5

Sample Output 1
2

Explanation
A[2] = 2

Constraints
-10^6<=Ai<=10^6
0<=N<=10^5
SOLUTION:
------------
function fixedPoint(n, arr) {
for(let i=0;i<n;i++){
if(arr[i]===i)
return i;
}
return -1;
}

***********************************************************************************
***********************************************************************************
*****

5.STRING RIGHT ROTATION:

Problem Description
You are given a string 'str' and an integer 'D'. Your task is to rotate
the given string right(clockwise) by 'D' units from the starting index. You are
required to return the rotated string.

Input format
First line contains a string str. Second line contains an integer D.

Output format
Return the rotated string.

Sample Input 1
learnbydoing 3

Sample Output 1
inglearnbydo

Explanation
In the right rotation, the substring of length 'D' = 3 from the end is
"ing", this substring is removed from the end and attached to the beginning of the
string(i.e. clockwise).

Constraints
1 <= |str| <= 10^5 1 <= D <= 10^5

SOLUTION:
----------
function rightRotation(str,D) {
if (str.length === 0) return str; // Edge case: empty string
const n = str.length;
D %= n; // Handle cases where D is greater than string length
return str.slice(n - D) + str.slice(0, n - D);
}

***********************************************************************************
***********************************************************************************
*****

6.Giant Army:

Problem Description
The planet named GiantX (the citizens of this planet are very very
tall, some people can be upto 10^9 cm tall) is on the verge of a war with a
different planet. To prepare for this, different army battalions are now
recruiting warriors to save the planet. Every battalion has a different minimum
height criteria for selecting warriors. There are a total of N
people who want to join the army and we are given their heights. There are Q
battalions and we are given minimum height requirements for each battalion.
For each battalion print how many people are eligible to join.

Input format First line contains two space separated integers N and Q
Second line contains N space separated integers A[i] representing the heights
of N people.
Next Q lines contain one integer (x[j]) each, representing the minimum height
required to join the Qth battalion.

Output format
Print Q lines.
The jth line should contain the number of people who are eligible to
join the jth battalion.
Sample Input 1
3 1
100 160 130
120

Sample Output 1
2

Explanation 1
There are 3 people with heights 100, 160 and 130. There is only one
battalion with the minimum height required to join the battalion being 120. There
are two such people (height > 120). Thus, the required answer is 2.

Sample Input 2
5 5
1 2 3 4 5
6
5
4
3
2

Sample Output 2
0
1
2
3
4

Explanation 2
The minimum height required to join the first battalion is 6. Not a
single person has a height of at least 6. Thus the answer is 0.

The minimum height required to join the second battalion is 5. Only the
fifth person has a height of at least 5. Thus the answer is 1.

The minimum height required to join the third battalion is 4. The fifth
and the fourth person has a height of at least 4. Thus the answer is 2.

The minimum height required to join the fourth battalion is 3. Third,


fourth and the fifth person has a height of at least 3. Thus the answer is 3.

The minimum height required to join the fifth battalion is 2. Second,


third, fourth and the fifth person has a height of at least 5. Thus the answer is
4.

Constraints
1 <= N, Q <= 2*10^5

1 <= A[i] <= 10^9

1 <= x[j] <= 10^9

SOLUTION:
----------
function giantArmy(N,Q,A,req) {
A.sort((a, b) => a - b); // sort the heights in ascending order
let res = [];
for (let i = 0; i < Q; i++) {
let left = 0, right = N;
while (left < right) {
let mid = Math.floor((left + right) / 2);
if (A[mid] < req[i]) {
left = mid + 1;
} else {
right = mid;
}
}
// the number of people who are eligible to join the battalion
let eligible = N - left;
res.push(eligible);
}
return res;
}
***********************************************************************************
***********************************************************************************
*****
7.CAPITALISE:

Problem Description
Given a paragraph of words, capitalize the first character of each word
and return the paragraph.

Input format
First line contains a string - The paragraph.

Output format
Print the paragraph after capitalizing each word.

Sample Input 1
the quick Brown fox jumps over The lazy dog.

Sample Output 1
The Quick Brown Fox Jumps Over The Lazy Dog.

Explanation
Each word has it’s first character capitalized

Constraints
Length of paragraph < 100.

The paragraph contains spaces, lowercase and uppercase characters.


----------
SOLUTION:
----------
function capitaliseBasic(Paragraph){
let s=Paragraph.split(" ");
return s.map(x=>x.charAt(0).toUpperCase()+ x.slice(1)).join(" ");

}
***********************************************************************************
***********************************************************************************
*****
8.COUNT NUMBER OF PRIME LESS THAN N:

Problem Description
Count the number of prime numbers less than a non-negative number, n.

Input format
Single line containing one integer N

Output format
Single line containing one number denoting the number of prime numbers
less than N

Sample Input 1
10

Sample Output 1
4

Explanation 1
There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

Constraints
0<=N=100000

SOLUTION:
---------
function countPrime(n){
let isPrime=new Array(n).fill(0);
for(let i=2;i<n;i++){
isPrime=true;
}
for(let i=2;i*i<n;i++){
if(isprime[i]){
for(let j=i;j<n;j=j+i){
isPrime[i]=false;
}
}
}
let count=0;
for(let i=2,i<n;i++){
if(isPrime[i]){
count++;
}
}
return count;
}

***********************************************************************************
***********************************************************************************
*****
9.REMOVE DUPLICATES FROM SORTED ARRAY

Problem Description
Given a sorted array, remove all duplicates such that each element
occurs at most once in the array. Return the length of the modified array.

Note : The input array should be modified in-place i.e. no extra memory
should be allocated to any other array and the question should be solved by using
O(1) memory.
Input format
There are two lines of input.

The first line consists of an integer N, which denotes the size of the
input array

The second line consists of N space separated integers, which acts as


our input array.

Output format
Prints the size of the modified array which consists of no duplicates.

Function Definition
Complete the function removeDuplicates.

removeDuplicates has the following parameters :

nums : An array of numbers in the sorted order

removeDuplicates returns :

int : An integer denoting the size of the modified array.

Constraints
0 <= N <= 10^6

1 <= A[i] <= 10^9

where A[i] denotes the ith element of the input array.

Sample Input 1
7

2 4 4 4 6 8 8

Sample Output 1
4

Explanation 1
The array can be modified to [2,4,6,8] after removing all duplicates
ensuring that all elements occur once. The length of this array is 4 , hence 4 is
the output.

Sample Input 2
4

2 2 3 11

Sample Output 2
3

Explanation 2
The array can be modified to [2,3,11] after removing all duplicates
ensuring that all elements occur once. The length of this array is 3 , hence 3 is
the output.

SOLUTION
--------
function removeDuplicates(n,arr){
let i=1;
let j=1;
while(j<n){
if(arr[j]!==arr[j-1]){
arr[i]=arr[j];
i++;
}
j++;
}
return i;

}
***********************************************************************************
***********************************************************************************
*****
10.LARGEST FIBINNOCI NUMBER LESS THAN THE NUMBER:

Problem Description
Given a number N, you have to find the largest Fibonacci number which is less
than N.

Input Format
First line contains an integer T - Number of test cases.

Next T lines each have a given number N

Output Format
Print the answer for each test case in a separate line.

Constraints
T <= 10^4

0 < N <= 10^9

Sample Input 1
2

13

Sample Output 1
5

Explanation 1
In the first test case the largest Fibonacci number less than 6 is 5.

In the second test case the largest Fibonacci number less than 13 is 8 (the
next Fibonacci number after 8 is 13 which is equal to the number N i.e. 13)

SOLUTION
--------
function largestFibinnociNumber(n){
if(n==1) return 0;
let a=0;
let b=1;
while(a+b<n){
let temp=a+b;
a=b;
b=temp;

}
return b;
}

***********************************************************************************
***********************************************************************************
*****

11.SECOND LARGEST

Problem Description
Given an array of n integers. Find the second maximum element in the given
array. If the 2nd largest element doesn't exist then return -1.

Input format
First line contains integer n.

Next line contains n space separated integers.

Output format
Return the second maximum element in the array.

Sample Input 1
6

12 35 1 10 34 1

Sample Output 1
34

Explanation
The largest element of the array is 35 and the second largest element is 34.

Sample Input 2
3

10 5 10

Sample Output 2
5

Explanation
The largest element of the array is 10 and the second largest element is 5.

Constraints
2 <= n <= 10^4

1 <= element of array <= 10^5


SOLUTION:
---------
function secondLargestNumber(arr){

let res= arr.sort((a,b)=> b-a)


.filter(function(item,pos,arr) {
return item != arr[pos - 1];
})
[1] || -1;

return res;

}
***********************************************************************************
***********************************************************************************
*****
12.VALID PALINDROME BASIC: [Two Pointers]

Problem Description
Given a string, determine if it is a palindrome, considering only alphanumeric
characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Input format
First line contains a string.

Output format
Print true if the given string is a palindrome; otherwise, print false.

Sample Input 1
A man, a plan, a canal: Panama

Sample Output 1
true

Explanation
"amanaplanacanalpanama" is a palindrome.

Sample Input 2
race a car

Sample Output 2
false

Explanation
"raceacar" is not a palindrome.

Constraints
1 <= s.length <= 2 * 10^5

SOLUTION:
--------
function isPalindrome(s){
s=s.replace(/[^a-zA-Z0-9]/g,'').toLowerCase();
let start=0;
let end=s.length-1;
while(start<end){
if(s[start] !== s[end]){
return false;

}
else{
start++;
end--;
}
}
return true;
}
***********************************************************************************
***********************************************************************************
*****

13.BOARD EXAMS

Problem Description
N students appeared for the board exams from a class. The answer of each student is
a string (a single word). You are assigned the task of checking how many answers
are copied. You have to check each consecutive pair of answers (words), to see if
they have the same starting character and ending character. This implies a copy.
Return the count of such copying.

Input format
First line contains an integer n denoting the number of answers.

Second line contains n space separated answers (Note that each answer is a word)

Output format
An integer representing how many copying instances were found.

Sample Input 1
4

abcd abdd da dd

Sample Output 1
1

Explanation1
The first character of both answer[0] and answer[1] is 'a', and last one is - 'd'.
So this is copied.

The first character of words[1] is 'a', but the first character of words[2] is 'd'.
So this is not copied.

The last character of words[2] is 'a', but the last character of words[3] is 'd'.
So this is not copied.

Constraints
1 <= n <= 1000

SOLUTION
--------
function copyCount(n,v){
let copyingCount=0;
for(let i=0;i<n-1;i++){
let firstword=v[i];
let secondword=v[i+1];
if(firstword[0]===secondword[0] && firstword.slice(-1)===secondword.slice(-1))
copyingCount++;
}
return copyingCount;

}
***********************************************************************************
*************************************************************
*********
14.EVALUATE IF THE GIVEN PARANTHESIS COMBINATION IS BALANCED:[STRING, STACK]

Problem Description
Given a string S containing the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.

For an input string to be valid:

Open brackets must be closed by the same type of brackets.( can be closed by ) only

Open brackets must be closed in the correct order. ([]) is valid, ([)] is not.

Note: An empty string is also considered valid.

Input format
One line containing a string with a bracket sequence.

Output format
Return "true" if balanced, false otherwise.

Constraints
0 <= | S | <= 10^5

Sample Input 1
()[]{}

Sample Output 1
true

Explanation 1
The given sequence of brackets is valid as per the rules specified.

Sample Input 2
([)]

Sample Output 2
false

Explanation 2
The given sequence of brackets is invalid as per the rules specified.

SOLUTION
--------
function validParanthesis(s){
let stack=[];
for(let i=0;i<s.length;i++){
let lastopen=stack[stack.length-1];
if(s[i]==="(" || s[i]==="[" || s[i]==="{"){
stack.push(s[i]);
}
else if(s[i]===")" && lastOpen==="(" || s[i]==="]" && lastopen==="[" ||
s[i]==="}" && lastOpen==="{"){
stack.pop();
}else{
return false;
}

}
if(stack.length>0){
return false;
}else{
return true;
}
}
***********************************************************************************
****************************************************************************

15.Find the length of the longest substring that has no repeating characters:
[Hash Map, String, Two Pointers]

Problem Description
Given a string, find the length of the longest substring which has no repeating
characters.

Input format
Input is a string.

Output format
Output is an integer representing the longest substring with no repeating
characters.

Sample Input 1
aabcccbcb

Sample Output 1
3

Explanation 1
"abc" is the longest substring with no repeating characters.

Sample Input 2
cdddddd

Sample Output 2
2

Explanation 2
"cd" is the longest substring with no repeating characters.

SOLUTION
--------
function longestSubstringWithoutRepeatingCharacter(s) {
let letter=s.split("");
let max=0;
let map=new Map();
for(let i=0;i<letter.length;++){
if(!map.has(letter[i])){
map.set(letter[i],i);
}
else{
i=map.get(letter[i]);
map.clear();
}
if(max<map.length){
max=map.length
}
}
return max;
}
***********************************************************************************
*************************************************************************

16. Find the smallest missing integer in an unsorted array [Hash Map, Array]

Problem Description
Given an unsorted array of integers, find the smallest missing positive integer.
The space complexity need not be O(1), you can also implement a O(N) space
complexity solution.

Input format
There are 2 lines of input.

First line contains 1 integer N - Number of elements in the array.

Second line contains space separated N integers.

Output format
Print the smallest missing positive integer.

Sample Input 1
4

3 4 -1 1

Sample Output 1
2

Explanation 1
2 is the smallest positive integer which is missing as 1 is already present in the
array. Note that 0 will not be considered as positive.

Constraints
N <= 200000

-2 ^ 31 <= Range of values <= 2 ^ 31 - 1

SOLUTION:
---------
function firstMissingPositive(n, arr) {

let map=new Map();


for(let num of arr){
if(!map.has(num)){
map.set(num);
}
}
for(let i=0;i<=n+1;i++){
if(!map.has(i)){
return i;
}
}
}
***********************************************************************************
***********************************************************************************
*****
******
17. Given a string, reverse it using stack [Recursion, String, Two Pointers]

Problem Description
Reverse the given string using stack.

Input format
First-line will be a single string.

Output format
Print the reverse of the string in a single line.

Sample Input 1
abc

Sample Output 1
cba

Sample Input 2
aaa

Sample Output 2
aaa

Constraints
1 <= length(S) <= 200000

SOLUTION:
---------

class{

constructor(){
this.elements=[];
}
push(element){
this.elements.push(element);
}
pop(){
if(this.elements.length===0) return "underflow situation";
else return this.elements.pop();
}
isEmpty(){
if(this.elements.length>0) return false;
else return true;
}

function reverseString(str){
let stack=new Stack();
let rev=" ";
let i=0;
while(i!==str.length){
stack.push(str[i]);
i++;
}
// console.log(stack);
while(!stack.isEmpty()){
rev +=stack.pop();
i++;
}
return rev;

***********************************************************************************
***********************************************************************************
*****

18. Richest Customer Wealth [Implementation]

Problem Description
You are given an m x n integer grid accounts where accounts[i][j] is the amount of
money the ith customer has in the jth bank. Return the wealth that the richest
customer has.

A customer's wealth is the amount of money they have in all their bank accounts.
The richest customer is the customer that has the maximum wealth.

Input format
A matrix of size m x n.

Output format
A single integer denoting the amount of money they have in all their bank accounts.
The richest customer is the customer that has the maximum wealth.

Sample Input 1
2

1 2 3

3 2 1

Sample Output 1
6

Explanation
1st customer has wealth = 1 + 2 + 3 = 6

2nd customer has wealth = 3 + 2 + 1 = 6

Both customers are considered the richest with a wealth of 6 each, so return 6.

Constraints
m == accounts.length

n == accounts[i].length
1 <= m, n <= 50

1 <= accounts[i][j] <= 100

SOLUTION
--------
function richestCustomerWealth(accounts){
const
wealthyArray=accounts.map(customer=>customer.reduce((acc,value)=>acc+value,1));
return Math.max(...wealthyArray);
}

***********************************************************************************
***********************************************************************************
*****

19. Find intersection of 2 arrays [Array,Two Pointers,Hash Map]

Problem Description
Given two integer arrays nums1 and nums2, return an array of their intersection.
Each element in the result must appear as many times as it shows in both arrays and
you may return the result in any order.

Input format
The first line contains two integers N and M, the sizes of the two arrays. The
second line contains the N elements belonging to the array nums1. The third line
contains the M elements belonging to the array nums2.

Output format
Return the intersection of the two arrays (also include duplicates in the result).

Sample Input 1
4 2

1 2 2 1

2 2

Sample Output 1
2 2

Explanation
The elements in [2,2] are common to both arrays.

Sample Input 2
3 5

4 9 5

9 4 9 8 4

Sample Output 2
4 9

Explanation
[4, 9] are present in both arrays. [9, 4] will also be accepted as the answer.

Constraints
1 <= N, M <= 1000

0 <= nums1[i], nums2[i] <= 1000

SOLUTION:
---------
function intersectionOfTwoArrays2(N,M,nums1,nums2) {
let n=Math.min(N,M);
let counter={};
for(let num of nums1){
counter[num]=(counter[num] || 0) + 1;
}
let res=[];
for(let num of nums2){
if(counter[num]>0){
res.push(num);
counter[num] -= 1;
}
}
return res;
}

***********************************************************************************
***********************************************************************************
*****

20. Given a column title as it appears in an excel sheet, return its corresponding
column number [String,Math]

Problem Description
Given a column title as it appears in an Excel sheet, return its corresponding
column number.

For example:

A -> 1

B -> 2

C -> 3

...

...

...

Z -> 26

AA -> 27

AB -> 28

...

...
...

Input format
You will be given a string of Capital English Letters.

Output format
Print the column number corresponding to this string.

Sample Input 1
A

Sample Output 1
1

Sample Input 2
AB

Sample Output 2
28

Sample Input 3
ZY

Sample Output 3
701

Constraints
1 <= |s| <= 12

SOLUTION:
--------
function excelSheetColumnNumber(s)
{
for(let i=0;i<s.length;i++){
let value= s.charCodeAt(i)-('A').charCodeAt(0) + 1;
let res=res * 26 + value;
}
return res;
}

***********************************************************************************
***********************************************************************************
*****

21. Last Word Length [Implementation]

Problem Description
Given a string s consisting of words and spaces, return the length of the last word
in the string.

A word is a maximal substring consisting of non-space characters only.

Input format
The single line contains a string.

Output format
A single integer
Sample Input 1
Hello World

Sample Output 1
5

Explanation
The last word is "World" with a length of 5.

Constraints
1 <= s.length <= 104

s consists of only English letters and spaces ' '.

There will be at least one word in s.

SOLUTION:
--------

function lastWordLength(s){

let i=s.length-1;
while(i>0 && s[i]===" "){
i--;
}
let j=i;
while(j>0 && s[j]!==" "){
j--;
}
return i-j;
}

***********************************************************************************
***********************************************************************************
*****
22. Backspace String Compare [Stack]

Problem Description
Given 2 strings S and T containing lowercase and '#' characters. You have to check
whether these 2 strings are same or not when typed into an editor('#' being the
backspace character).

Note: Backspacing an empty string remains an empty string only.

For eg. a#bc means bc, and a##bcd means bcd.

Input format
There are 2t+1 lines of input.

First line contains an integer tests - Number of test cases.

First line of each test case contains a string S.

Second line of each test case contains a string T.

Output format
Print true if the 2 strings are same otherwise false, for each test case print in a
different line.
Function definition
You have to complete the given function. It accepts two parameters - the two
strings, and returns a boolean value, true if S and T are same and false if not.

Sample Input 1
2

as#sddff#

aa#sddf

a##b

ab

Sample Output 1
true

false

Explanation
In first test case both the strings become "asddf" when typed into an editor.

In second test case the string becomes "b" and "ab" which are not equal.

Constraints
1 <= tests <= 10

1 <= Length of each string <= 10^5

SOLUTION:
--------
function backSpaceStringCompare(S,T){
const processString=(s)=>{
let stack=[];
for(let char of stack){
if(char !== "#"){
stack.push(char);
}else{
stack.pop();
}
}
return stack.join("");
}
let first=processString(S);
let second=processString(T);
return first===second;
}

***********************************************************************************
***********************************************************************************
*****
23.Frequency Of Words [Implementation]

Problem Description
Given a string str, the task is to find the frequency of each word in a string.
Input format
A single line containing a string.

Output format
This line will contain the frequency of all distinct words arrange in
lexicographically increasing order.

Sample Input 1
nikhil nikhil mayank ankit ankit ankit

Sample Output 1
3 1 2

Explanation
ankit - 3

mayank - 1

nikhil - 2

Here the distinct words, ankit , mayank and nikhil are arranged lexicographically.

Constraints
1 <= s.length <= 104

s consists of only English letters and spaces.

There will be at least one word in s.

SOLUTION:
--------
function frequencyOfWords(str){
let words = str.split(" ");
let map = new Map();

// Count frequency of each word


for (let word of words) {
if (map.has(word)) {
map.set(word, map.get(word) + 1);
} else {
map.set(word, 1);
}
}

// Sort the keys lexicographically


let sortedWords = Array.from(map.keys()).sort();

// Output frequencies in the order of sorted words


let frequencies = [];
for (let word of sortedWords) {
frequencies.push(map.get(word));
}

return frequencies;
}
***********************************************************************************
***********************************************************************************
*****
24.Key Pair [Implementation]
Problem Description
Given an array Arr of N positive integers and another number X. Determine whether
or not there exist two elements in Arr whose sum is exactly X.

Input format
Line 1:A single integer N

Line 2:An array Arr

Line 3:A single integer X

Output format
1 if there exist two elements in Arr whose sum is exactly X else 0.

Sample Input 1
6

1 4 45 6 10 8

16

Sample Output 1
Yes

Explanation
Arr[3]+Arr[4]=6+10=16.

Constraints
1 ≤ N ≤ 10^5

1 ≤ Arr[i] ≤ 10^5

SOLUTION:
--------
function keyPair(arr,arr_size,sum){
let map=new Map();
for(let i=0;i<arr_size;i++){
let compliment=sum-arr[i];
if(map.has(complement)) return 1;
else map.set(arr[i],true);
}
return 0;
}
***********************************************************************************
***********************************************************************************
*
25.Find if an array contains any duplicates [Sorting, Hash Map,Array]

Problem Description
Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array,
and it should return false if every element is distinct.

Input format
First-line will contain an integer n denoting the number of numbers in the list.

Next line will contain n space-separated integers.


Output format
Print "false" if no duplicate found otherwise “true”.

Sample Input 1
4

1 2 3 1

Sample Output 1
true

Sample Input 2
4

1 2 3 4

Sample Output 2
false

Sample Input 3
10

1 1 1 3 3 4 3 2 4 2

Sample Output 3
true

Constraints
0<= n <=1000000

-1e6 <= a[i] <= 1e6

Solution:
--------
function containsDuplicate(nums){

let map=new Map()


for(let num of nums){
if(map.has(num)) return true;
else map.set(num,1)
}
return false;
}
***********************************************************************************
***********************************************************************************
**********
26. Max and Min [Implementation,Array]

Problem Description
Given an array A of size N of integers. Your task is to find the sum of the minimum
and maximum elements in the array.

Input format
The first line contains N - the size of the array.

The next line contains N distinct elements of array A.

Output format
The only line containing the required answer.

Sample Input 1
5

-2 1 -4 5 3

Sample Output 1
1

Explanation
min = -4, max = 5. Sum = -4 + 5 = 1

Constraints
1 <= N <= 10^5

-10^9 <= Ai <= 10^9

SOLUTION:
--------

function maxMin(arr, N) {

if (N === 0 || !arr || arr.length !== N) {


return 0;
}

let min = arr[0];


let max = arr[0];

for (let i = 1; i < N; i++) {


if (arr[i] < min) {
min = arr[i];
} else if (arr[i] > max) {
max = arr[i];
}
}

let sum = min + max;

return sum;

}
***********************************************************************************
***********************************************************************************
****
27.Determine whether a string can be increasing or decreasing [Implementation,
Array]

Problem Description
The sports teacher told the students of a class to assemble in the playground. The
order in which the students are standing in the playground is given in an array
where each element of the array represents the height of student[i]. Rahul, the
class leader, is asked to check if the heights of students at even positions are
monotonic (i.e either in non-decreasing order or non-increasing order). Say
"increasing" if the students at even positions are standing in non-decreasing order
of their heights. Else say “decreasing” if the students at even positions are
standing in non-increasing order. Else, say “none”.

Non-decreasing order, for example, is 1,1,2,3,4,4. This basically means increasing


order, but a number can also be equal to the previous number.
Similarly non-increasing order means decreasing order, where a number can be equal
to the previous number.

Input format
First line contains an integer n (number of students)

Second line contains n space separated integers.

Output format
A string, can be "decreasing", “increasing” or “none”

Sample Input 1
6

12 65 15 72 19 72

Sample Output 1
increasing

Explanation
Students on even positions are student[0], student[2], and student[4], i.e., 12,
15, and 19. Since 12 < 15 < 19, the answer is "increasing".

Constraints
3<=N<=100000

-100000<=student[i]<=100000

SOLUTION:
--------

function classRepresentative(numbers) {
let increasing = 0;
let decreasing = 0;
let n = numbers.length;

for (let i = 0; i < n - 2; i += 2) {


if (numbers[i] < numbers[i + 2]) {
increasing++;
} else if (numbers[i] > numbers[i + 2]) {
decreasing++;
} else {
return "none";
}
}

if (increasing > 0 && decreasing === 0) {


return "increasing";
} else if (decreasing > 0 && increasing === 0) {
return "decreasing";
} else {
return "none";
}
}
***********************************************************************************
***********************************************************************************
*****
28. Find the value of an arithmetic expression in Reverse Polish Notation
[Stack,Math,Array]

Problem Description
You are given a string representing an arithmetic expression in Reverse Polish
Notation(RPN), also known as Postfix notation.

You have to evaluate the value of the expression and return the anwer.

Valid operators are +, -, *, /. Each operand may be an integer or another


expression.

Note:

Division between two integers should truncate toward zero.

The given expression is always valid. That means the expression would always
evaluate to a result and there won't be any divide by zero operation.

Input format
One line containing one string S denoting the expression in Reverse Polish Notation
where each element is separated by space.

Output format
One line denoting the output of the arithmetic expression.

Function definition
You have to implement the given function. It accepts one argument - an array of
strings. Each of these strings represents one token - either an operand, or an
operator. You have to return the final answer in integer.

Sample Input 1
2 1 + 3 *

Sample Output 1
9

Explanation 1
(2+1)*3 = 9

Constraints
1<=|S|<=100

SOLUTION:
--------
function reversePolishNotation(expression) {
let stack = [];

for (let i = 0; i < expression.length; i++) {


if (!isNaN(parseInt(expression[i]))) {
stack.push(parseInt(expression[i]));
} else {
let operand2 = stack.pop();
let operand1 = stack.pop();
switch (expression[i]) {
case '+':
stack.push(operand1 + operand2);
break;
case '-':
stack.push(operand1 - operand2);
break;
case '*':
stack.push(operand1 * operand2);
break;
case '/':
stack.push(Math.trunc(operand1 / operand2));
break;
}
}
}

return stack.pop();

***********************************************************************************
***********************************************************************************
********
29. Find the maximum number of points that lie on the same straight line [Math,
Hash Map]

Problem Description
Given n points on a 2D plane, find the maximum number of points that lie on the
same straight line.

Input format
First line contains one number N denoting the number of points.

Next N lines contain 2 numbers X, Y denoting X coordinate and Y coordinate of ith


point.

Output format
One number denoting the number denoting the maximum number of points that lie on
the same straight line.

Sample Input 1
3

1 1

2 2

3 3

Sample Output 1
3

Explanation 1
One straight line can be drawn going through all 3 of the points given.
Sample Input 2
6

1 1

3 2

5 3

4 1

2 3

1 4

Sample Output 2
4

Explanation 2
One straight line can be drawn going through 4 of the points - (1 4), (2 3), (3 2)
and (4 1)

Constraints
1<=N<=1000

-1000000<=X,Y<=1000000

SOLUTION:
---------

function gcd(a, b) {
if (!b) {
return a;
}
return gcd(b, a % b);
}

function maxPointsOnLine(points) {
let N = points.length;
if (N < 2){
return N;
}

let maxPoint = 0;

for (let i = 0; i < N; i++) {


let curMax = 0;
let overlapPoints = 0;
let verticalPoints = 0;

let slopeMap = new Map();

for (let j = i + 1; j < N; j++) {


if (points[i][0] === points[j][0] && points[i][1] === points[j][1]) {
overlapPoints++;
} else if (points[i][0] === points[j][0]) {
verticalPoints++;
} else {
let yDif = points[j][1] - points[i][1];
let xDif = points[j][0] - points[i][0];
let g = gcd(xDif, yDif);

yDif = Math.floor(yDif / g);


xDif = Math.floor(xDif / g);

let slope = `${yDif}/${xDif}`;


slopeMap.set(slope, (slopeMap.get(slope) || 0) + 1);
curMax = Math.max(curMax, slopeMap.get(slope));
}
}

curMax = Math.max(curMax, verticalPoints) + overlapPoints + 1;


maxPoint = Math.max(maxPoint, curMax);
}

return maxPoint;
}

***********************************************************************************
***********************************************************************************
************
30. Find the string with all odd length words reversed [String, Implementation]

Problem Description
Rahul works as a secret agent. He wants to send a message to his teammates and at
the same time he doesn’t want anyone else to understand his message, except his
teammates.

So, he decided to reverse all the words in the message which have an odd length.
Print the final message which he will be sending to his teammates.

Input format
Input message string

Output format
Print the string with all odd length words reversed

Sample Input 1
One Two three Four

Sample Output 1
enO owT eerht Four

Explanation
One is of odd length, so reverse it.

Two is of odd length, so reverse it.

three is of odd length, so reverse it.

Four is of even length, so don't reverse it.


Constraints
1<=message.length<=100

SOLUTION:
--------

function secretAgentII(s) {
const words = s.split(' ');

for (let i = 0; i < words.length; i++) {


if (words[i].length % 2 !== 0) {
words[i] = words[i].split('').reverse().join('');
}
}

return words.join(' ');


}
***********************************************************************************
***********************************************************************************
31. Diagonal Sum Basic [Implementation]

Problem Description
Given an matrix of dimension n*n. Find the sum of elements present at principal
diagonal of the matrix.

Input format
First line contains integer n.

In next n lines each line contains n elements.

Output format
An integer representing the sum of diagonal elements.

Sample Input 1
4

1 2 3 4

1 2 4 5

2 3 3 4

1 1 2 3

Sample Output 1
9

Explanation
elements at diagonal are 1, 2, 3, 3 and their sum is 9.

Constraints
1 <= n <= 100

0 <= element of matrix <= 10^5

SOLUTION:
---------
function diagonalSum(n, matrix) {

let sum=0;
for(let i=0;i<n;i++){
for(let j=i;j<n;j++){
if(i===j) sum=sum+matrix[i][j];
}
}
return sum;
}

***********************************************************************************
*****************************************************************************
32.Reverse order of words in given string [Stack,String,Implementation]

Problem Description
A word is defined as a sequence of non-space characters. The words in s will be
separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two
words.

The returned string should only have a single space separating the words.

Do not include any extra spaces.

Input format
String s.

Output format
The function should return a string of the words in reverse order concatenated by a
single space.

Sample Input 1
hello world

Sample Output 1
world hello

Explanation
The given words after being reversed gives:world hello

Your reversed string should not contain leading or trailing spaces.

Constraints
1 <= s.length <= 10^5

s contains English letters (upper-case and lower-case), digits, and spaces ' '.

There is at least one word in s.

SOLUTION:
---------
function reverseWordsInAString(s) {
return s.split(' ').reverse().join(' ').replace(/^\s+|\s+$/gm,'');
}
***********************************************************************************
*******************************************************************************
33.Determine if a number is happy [Implementation]

roblem Description
Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any
positive integer, replace the number by the sum of the squares of its digits, and
repeat the process until the number equals 1 (where it will stay), or it loops
endlessly in a cycle which does not include 1. Those numbers for which this process
ends in 1 are happy numbers.

Input format
First-line contains 1 integer N.

Output format
Print true or false.

Sample Input 1
19

Sample Output 1
true

Explanation 1
1^2 + 9^2 = 82

8^2 + 2^2 = 68

6^2 + 8^2 = 100

1^2 + 0^2 + 0^2 = 1

Constraints
-2^31 <= N <= 2^31-1

SOLUTION
--------
function digitSquareSum(n){
let sum=0;
while(n>0){
const d=n%10;
sum+=d*d;
n=Math.floor(n/10);
}
return sum;
}
function happyNumber(n){
const seenNumbers=new Set();
while(n!=1){
const newNum=digitSquareSum(n);
if(seenNumbers.has(newNum))
return false;
seenNumbers.add(newNum);
n=newNum;

}
return true;
}

***********************************************************************************
*************************************************************************

34.In an array, find two numbers such that they add up to a specific target [Hash
Map,Array]

Problem Description
Given an array of integers as input, output the indices of two numbers in the array
which add up to a specified target.

Assume that each input would have exactly one solution and you cannot use the same
element twice. If 2 different elements have the same value, they can be used.

Print the indices in increasing order.

Input format
First line contains an Integer N that represents the number of elements in the
array.

Second line contains N space separated integers, which are members of the array.

Third line contains an integer X, which is the target value.

Output format
Print two space separated indices(in increasing order) of the numbers which add up
to the specified target.

Constraints
2 <= Length of array <= 100000

1 <= Range of values <= 1000000

Sample Input 1
5 --> Number of elements in array

2 4 5 9 8 --> Array elements

7 --> Target sum value

Sample Output 1
0 2

Explanation 1
Since 0 and 2 are the indices where the numbers 2 and 5 which add up to 7 are seen

SOLUTION
--------
function twosum(n,arr,target){
let map=new Map();
let i=0;
for(let i=0;i<n;i++){
let compliment=target-arr[i]
if(map.has(compliment)) return map.get(arr[compliment],i)
else map.set(arr[i],i);
}

***********************************************************************************
*************************************************************************

35.Reverse the given string [String, Implementation]

Problem Description
Write a function that reverses a string.

Input format
First line will be a single string

Output format
1<=size(S)<=200000

Sample Input 1
abc

Sample Output 1
cba

Explanation
cba is reverse of abc.

Sample Input 2
aaa

Sample Output 2
aaa

Explanation
aaa is reverse of aaa.

Constraints
Print the reverse of the string in a single line.

Solution:
--------

function reverseString(s){
return s.split("").reverse().join("");
}

***********************************************************************************
*************************************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

You might also like