Fibonacci Sequence:
function generateFibonacci(n) {
const fibonacci = [0, 1];
for (let i = 2; i < n; i++) {
fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
}
return fibonacci.slice(0, n);
}
// Example usage
console.log(generateFibonacci(10)); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
2.Prime Number Check
function isPrime(num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 === 0 || num % 3 === 0) return false;
let i = 5;
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) return false;
i += 6;
}
return true;
}
// Example usage
console.log(isPrime(11)); // true
console.log(isPrime(15)); // false
Sum of Natural Numbers
function sumOfNaturalNumbers(n) {
return (n * (n + 1)) / 2;
}
// Example usage
console.log(sumOfNaturalNumbers(10)); // 55
Array Rotation
function rotateArray(arr, k) {
const n = arr.length;
k = k % n;
const rotated = [...arr.slice(n - k), ...arr.slice(0, n - k)];
return rotated;
}
// Example usage
console.log(rotateArray([1, 2, 3, 4, 5], 2)); // [4, 5, 1, 2, 3]
Find Maximum and Minimum in an Array
function findMaxMin(arr) {
if (arr.length === 0) return { max: undefined, min: undefined };
let max = arr[0];
let min = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
}
return { max, min };
}
// Example usage
console.log(findMaxMin([3, 5, 1, 9, 2])); // { max: 9, min: 1 }
Palindrome String Check
function isPalindromeString(str) {
const cleanStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
return cleanStr === cleanStr.split('').reverse().join('');
}
// Example usage
console.log(isPalindromeString("A man, a plan, a canal: Panama")); // true
console.log(isPalindromeString("hello")); // false
Binary Search Implementation
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // Target not found
}
// Example usage
console.log(binarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 7)); // 6
console.log(binarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11)); // -1
Armstrong Number Check
function isArmstrongNumber(num) {
const digits = num.toString().split('');
const power = digits.length;
const sum = digits.reduce((acc, digit) => {
return acc + Math.pow(parseInt(digit), power);
}, 0);
return sum === num;
}
// Example usage
console.log(isArmstrongNumber(153)); // true (1^3 + 5^3 + 3^3 = 153)
console.log(isArmstrongNumber(370)); // true (3^3 + 7^3 + 0^3 = 370)
console.log(isArmstrongNumber(123)); // false
Reverse a String
function reverseString(str) {
return str.split('').reverse().join('');
}
// Example usage
console.log(reverseString("hello")); // "olleh"
Two Sum Problem
function twoSum(nums, target) {
const numToIndex = {};
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (complement in numToIndex) {
return [numToIndex[complement], i];
}
numToIndex[nums[i]] = i;
}
return [-1, -1]; // No solution found
}
// Example usage
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]
Find Duplicate in an Array
function findDuplicate(nums) {
// Floyd's Tortoise and Hare (Cycle Detection)
let slow = nums[0];
let fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow !== fast);
slow = nums[0];
while (slow !== fast) {
slow = nums[slow];
fast = nums[fast];
}
return fast;
}
// Example usage
console.log(findDuplicate([1, 3, 4, 2, 2])); // 2
Longest Substring Without Repeating Characters
function lengthOfLongestSubstring(s) {
const charMap = new Map();
let maxLength = 0;
let start = 0;
for (let end = 0; end < s.length; end++) {
const currentChar = s[end];
if (charMap.has(currentChar)) {
start = Math.max(charMap.get(currentChar) + 1, start);
}
charMap.set(currentChar, end);
maxLength = Math.max(maxLength, end - start + 1);
}
return maxLength;
}
// Example usage
console.log(lengthOfLongestSubstring("abcabcbb")); // 3
console.log(lengthOfLongestSubstring("bbbbb")); // 1
console.log(lengthOfLongestSubstring("pwwkew")); // 3
Implement Merge Sort
function mergeSort(arr) {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid));
const right = mergeSort(arr.slice(mid));
return merge(left, right);
}
function merge(left, right) {
const result = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++;
}
}
return [...result, ...left.slice(leftIndex), ...right.slice(rightIndex)];
}
// Example usage
console.log(mergeSort([5, 3, 8, 4, 2, 1, 6])); // [1, 2, 3, 4, 5, 6, 8]
Kth Largest Element in an Array
function findKthLargest(nums, k) {
// Quick select algorithm
return quickSelect(nums, 0, nums.length - 1, nums.length - k);
}
function quickSelect(nums, left, right, kSmallest) {
if (left === right) return nums[left];
const pivotIndex = partition(nums, left, right);
if (pivotIndex === kSmallest) {
return nums[pivotIndex];
} else if (pivotIndex < kSmallest) {
return quickSelect(nums, pivotIndex + 1, right, kSmallest);
} else {
return quickSelect(nums, left, pivotIndex - 1, kSmallest);
}
}
function partition(nums, left, right) {
const pivot = nums[right];
let i = left;
for (let j = left; j < right; j++) {
if (nums[j] <= pivot) {
[nums[i], nums[j]] = [nums[j], nums[i]];
i++;
}
}
[nums[i], nums[right]] = [nums[right], nums[i]];
return i;
}
// Example usage
console.log(findKthLargest([3, 2, 1, 5, 6, 4], 2)); // 5
Palindrome Number
function isPalindromeNumber(x) {
if (x < 0) return false;
const str = x.toString();
const reverseStr = str.split('').reverse().join('');
return str === reverseStr;
}
// Example usage
console.log(isPalindromeNumber(121)); // true
console.log(isPalindromeNumber(-121)); // false
console.log(isPalindromeNumber(10)); // false
Move Zeros in an Array
function moveZeroes(nums) {
let nonZeroIndex = 0;
// Move all non-zero elements to the front
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
nums[nonZeroIndex] = nums[i];
nonZeroIndex++;
}
}
// Fill the rest with zeros
for (let i = nonZeroIndex; i < nums.length; i++) {
nums[i] = 0;
}
return nums;
}
// Example usage
console.log(moveZeroes([0, 1, 0, 3, 12])); // [1, 3, 12, 0, 0]
Maximum Subarray Problem (Kadane's Algorithm)
function maxSubArray(nums) {
let maxSum = nums[0];
let currentSum = nums[0];
for (let i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
// Example usage
console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // 6
Valid Parentheses
function isValidParentheses(s) {
const stack = [];
const brackets = {
'(': ')',
'[': ']',
'{': '}'
};
for (let char of s) {
if (char in brackets) {
stack.push(char);
} else {
const lastBracket = stack.pop();
if (brackets[lastBracket] !== char) {
return false;
}
}
}
return stack.length === 0;
}
// Example usage
console.log(isValidParentheses("()")); // true
console.log(isValidParentheses("()[]{}")); // true
console.log(isValidParentheses("(]")); // false
Climbing Stairs Problem
function climbStairs(n) {
if (n <= 2) return n;
let oneStepBefore = 2;
let twoStepsBefore = 1;
let ways = 0;
for (let i = 3; i <= n; i++) {
ways = oneStepBefore + twoStepsBefore;
twoStepsBefore = oneStepBefore;
oneStepBefore = ways;
}
return ways;
}
// Example usage
console.log(climbStairs(3)); // 3
console.log(climbStairs(5)); // 8
TCS NQT Coding Question – September Day 1 – Slot 1
Problem Statement –
A chocolate factory is packing chocolates into the packets. The chocolate packets here represent an array of N number of integer values. The task is to find the empty packets(0) of chocolate and push it to the end of the conveyor belt(array).
Example 1 :
N=8 and arr = [4,5,0,1,9,0,5,0].
There are 3 empty packets in the given set. These 3 empty
packets represented as O should be pushed towards the end of the array
Input :
8 – Value of N
[4,5,0,1,9,0,5,0] – Element of arr[O] to arr[N-1],While input each element is separated by newline
Output:
4 5 1 9 5 0 0 0
Example 2:
Input:
6 — Value of N.
[6,0,1,8,0,2] – Element of arr[0] to arr[N-1], While input each element is separated by newline
Output:
6 1 8 2 0 0
Online Compiler
TCS NQT Coding Question – September Day 1 – Slot 1Problem Statement –
Joseph is learning digital logic subject which will be for
his next semester. He usually tries to solve unit assignment problems before
the lecture. Today he got one tricky question. The problem statement is “A
positive integer has been given as an input. Convert decimal value to binary
representation. Toggle all bits of it after the most significant bit including
the most significant bit. Print the positive integer value after toggling all
bits”.
Constrains-
1<=N<=100
Example 1:
Input :
10 -> Integer
Output :
5 -> result- Integer
Explanation:
Binary representation of 10 is 1010. After toggling the
bits(1010), will get 0101 which represents “5”. Hence output will print “5”.
Online Compiler
TCS NQT Coding Question Day 1 Slot 2 – Question 1
Jack is always excited about sunday. It is favourite day,
when he gets to play all day. And goes to cycling with his friends.
So every time when the months starts he counts the number of
sundays he will get to enjoy. Considering the month can start with any day, be
it Sunday, Monday…. Or so on.
Count the number of Sunday jack will get within n number of
days.
Example 1:
Input
mon-> input String denoting the start of the month.
13 -> input integer denoting the number of days
from the start of the month.
Output :
2 -> number of days within 13 days.
Explanation:
The month start with mon(Monday). So the upcoming sunday
will arrive in next 6 days. And then next Sunday in next 7 days and so on.
Now total number of days are 13. It means 6 days to first
sunday and then remaining 7 days will end up in another sunday. Total 2 sundays
may fall within 13 days.
Online Compiler
TCS NQT Coding Question Day 1 Slot 2 – Question 2
Airport security officials have confiscated several item of
the passengers at the security check point. All the items have been dumped into
a huge box (array). Each item possesses a certain amount of risk[0,1,2]. Here,
the risk severity of the items represent an array[] of N number of integer
values. The task here is to sort the items based on their levels of risk in the
array. The risk values range from 0 to 2.
Example :
Input :
7 -> Value of N
[1,0,2,0,1,0,2]-> Element of arr[0] to arr[N-1], while
input each element is separated by new line.
Output :
0 0 0 1 1 2 2 -> Element after sorting based on
risk severity
Example 2:
input : 10 -> Value of N
[2,1,0,2,1,0,0,1,2,0] -> Element of arr[0] to arr[N-1],
while input each element is separated by a new line.
Output :
0 0 0 0 1 1 1 2 2 2 ->Elements after sorting based
on risk severity.
Explanation:
In the above example, the input is an array of size N
consisting of only 0’s, 1’s and 2s. The output is a sorted array from 0 to 2
based on risk severity.
Online Compiler
TCS NQT Coding Question Day 2 Slot 1 – Question 1
Given an integer array Arr of size N the task is to find the
count of elements whose value is greater than all of its prior elements.
Note : 1st element of the array should be considered in the
count of the result.
For example,
Arr[]={7,4,8,2,9}
As 7 is the first element, it will consider in the result.
8 and 9 are also the elements that are greater than all of
its previous elements.
Since total of 3 elements is present in the array that
meets the condition.
Hence the output = 3.
Example 1:
Input
5 -> Value of N, represents size of Arr
7-> Value of Arr[0]
4 -> Value of Arr[1]
8-> Value of Arr[2]
2-> Value of Arr[3]
9-> Value of Arr[4]
Output :
3
Example 2:
5 -> Value of N, represents size of Arr
3 -> Value of Arr[0]
4 -> Value of Arr[1]
5 -> Value of Arr[2]
8 -> Value of Arr[3]
9 -> Value of Arr[4]
Output :
5
Constraints
1<=N<=20
1<=Arr[i]<=10000
0 Comments