Virtusa Coding Questions with Answers

Virtusa Coding Questions with Solutions

Preparing Virtusa coding questions for Virtusa Online Test can be a game changer in clearing the technical stages of the hiring process. Whether you’re aiming for the Coder or Power Coder role, understanding the type of questions asked and practicing with the right approach is essential.

In this article, we’ve compiled some of the most commonly asked Sample Virtusa coding questions, along with detailed answers and explanations to help you sharpen your problem solving skills and improve your chances of selection. 

virtusa coding questions with solutions

You can checkout about Virtusa Neural Hackathon 2025 below….

Virtusa Recruitment Process Details....

CriteriaCoderPower Coder
PurposeStandard coding profile for general technical roles.Advanced coding profile for top performers or specialized roles.
No. of Coding Questions4 Questions3 Questions
Difficulty LevelModerateHard
Time Limit50 Minutes80 Minutes
Topics CoveredArrays, Strings, Recursion, Sorting, Searching, etc.Trees, Graphs, Dynamic Programming, Advanced Algorithms, etc.
Evaluation CriteriaLogic, Correctness an d Basic OptimizationEfficient Algorithm Design, Optimization and Edge Case Handling
Who Should Apply?Freshers with good coding fundamentalsCandidates aiming for higher packages or competitive tech roles
SalaryRs. 5 LPARs. 6.5 LPA

From here, you will get sample Virtusa Coding Questions with Solution to practice properly including Advanced Data Structures and Algorithms Concepts…..

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Sample Virtusa Coding Questions and Answers

Problem 1. Build Pattern:

Problem Statement: Ram has been given a task by his friend to built the trapezium, but ram mocked him to give him such easy problem.

So to make problem hard , his friend apply some conditions on the problems :

  • Length should be provided by the user
  • Trapezium should be filled with # and –
  • Trapezium should be half cut
  • Last line of trapezium should be only filled with –

Input: 5

Output:
####-####
###—###
##—–##
#——-#
———

Solution:

Problem 2: Minimum Sum Game

Problem Statement: Ram is a boy who is very interested in playing new games, so his mother took him to a puzzle game and asked him to solve it.

His mother gave some instructions to solve the puzzle game.

  • Now he has to follow all the given instructions while solving the game. His mother explained the step by step rule of the game and told that first you have to take n elements, after that you have to sum the digits of that n taken numbers.
  • After adding the digits of the taken number, He has to check that the sum of which digit numbers is minimum.
  • Now Ram has to find the minimum sum of digits of the number which he had taken in the beginning of the game.

Write a proper algorithmic code to solve that puzzle game.

Constraints :
1<=n<= 105

Input:
4 = number of elements
21 2 30 33 elements

Output:
2

Problem 3: Finding Sequence

Problem Statement: On Monday morning,the principal of a school in Noida thought that let’s do something different with the children today.

  • So the principal called different students to the assembly hall and formed a group of students from different classes of his school to explain to them the task they want to do today.
  • Now the principal explained to them that all the people you have gathered here are a group.
  • So the task is that all you have to do is that all the people who are in this group, you have to tell your roll number.
  • After collecting the roll numbers, you have to make a line according to the roll numbers in the ascending order.

And to check how many consecutive sub sequences are being formed in the line that is being formed according to these roll numbers?

  1. And Finally the main task is that we have to see, out of the consecutive sub-sequences that are being made according to the roll number, what is the maximum possible length of the consecutive sequence of n roll no. of students taken in the beginning ?
  2. Definition of consecutive sequence: Numbers that follow each other continuously in the order from smallest to largest are called consecutive numbers.

Constraints :

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Input:

  • 6 = number of elements
  • [100,4,200,1,3,2] = elements

Output:
4

Problem 4: Confused String

Problem Statement: Aditya and Mohan are two friends. Aditya said to Mohan, let’s do your brain test today and check whether you get confused or not.

To test Mohan’s brain, Aditya gives him two strings, a string S1 and a string S2.

Here string S1 = coaching and string S2 = coding

While instructing Mohan, Aditya said that the letters of both the strings are in lowercase. Now Mohan’s curiosity was increasing, So he asked Aditya what he has to do with these two strings.

Aditya instructs Mohan:

  • That he has to provide a solution to find the minimum number of characters that need to be appended at the end of the first string, so the second string becomes a subsequence of the first string.
  • All the letters of the second string have to be compared with the first string in order to confirm/prove that first string is a subsequence of the second string.
  • Now Mohan has to give the algorithmic solution to pass this brain test.

Definition of subsequence: Subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.

Constraints:

  • 1 <= s.length <= 10^5
  • String1 and string2 consist of only lowercase english letters

Input:
String 1 : coaching
String 2 : coding

Output:
4

Problem 5: Am I Panagram?

Problem Statement: Aman has given a sentence with a meaning, his task is to check whether the given sentence is panagram or not. Your task is to write an algorithmic code to help aman.
(Panagram is the sentence which complete all the english alphabet at least once)

Input:
6
abc defghu ijklmnbop qrstuvw xyy yz

Output:
True

These were some Sample Virtusa Coding Questions and Answers, go through them properly and prepare effectively.

If you want to prepare questions like these for Virtusa Coding Round, do checkout our Coding Dashboard.

FAQ's related Virtusa Power Coding Challenge

Answer:

The Virtusa recruitment process mainly includes 4 rounds:

Round 1: Online Assessment (Aptitude, Logical Reasoning, Verbal, Pseudocode, CS Fundamentals and Coding)

Round 2: Technical Interview

Round 3: Group Discussion or Managerial Round

Round 4: HR Interview

Answer:

  • Coder Profile: Includes 4 moderate-level coding questions to be solved in 50 minutes.
  • Power Coder Profile: Includes 3 high difficulty coding questions with 80 minutes to solve. It is designed for candidates aiming for advanced roles or higher packages.

Answer:

The Virtusa assessment includes the following sections:

  1. Quantitative Aptitude and Logical Reasoning
  2. Verbal Ability
  3. Pseudocode and Programming Fundamentals
  4. Computer Science Fundamentals (OS, DBMS, Data Structures)
  5. Coding (for Coder/Power Coder tracks)

Answer:

No. While Virtusa hires extensively through campus placements, it also conducts off-campus drives and open hiring challenges like Talent Titan or Power Programmer Challenges through platforms like HirePro, TalentTitan, and Superset.

 

Answer:

To be eligible for Virtusa On campus hiring, candidates must meet the following criteria:

  1. Must be from the B.E./B.Tech (CSE, IT, ECE, EEE, EIE) or MCA/M.Tech background.
  2. Should belong to the 2025 passing out batch.
  3. Must have 60% or above in 10th, 12th, and graduation (or equivalent CGPA).
  4. Should not have more than 1 active backlog at the time of applying.
  5. Must not have a gap of more than 1 year in education.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Flipkart Coding Questions and Answers

Sample Flipkart Coding Questions with Solution

Here, on Flipkart coding questions and answers page you will get sample DSA questions with solution which can be asked in Flipkart SDE 1 Coding Assessment.

Let you know that Flipkart mainly asks Data Structures and Algorithms based questions based Binary Search Tree, Graphs, Tries, Trees and Dynamic programming.

Checkout this page get all the Sample Flipkart Coding Questions with Solutions.

About Round 1 – Flipkart Coding Assessment

First stage of the Flipkart SDE-1 recruitment process is an online coding assessment, conducted on HackerRank

This round serves as an initial screening to evaluate your problem solving and coding skills.

  • Duration: 90 minutes

  • Platform: HackerRank

  • Number of Questions: 3 coding problems

  • Difficulty Level: Medium to Hard

  • Topics Covered:

    1. Binary Search Trees (BST)

    2. Tries (Prefix Trees)

    3. Tree and Graph Traversals (DFS, BFS)

    4. Graph Algorithms (Cycle detection, shortest paths, connected components)

    5. Dynamic Programming (Tabulation, memoization, optimization problems)

To succeed in this round, focus on writing clean, optimized code and thoroughly testing your solutions against edge cases.

After this round 2 Technical Interviews followed by Hiring Manager Round  will be conducted for assessing the candidates.

Practice Coding Questions:

Checkout PrepInsta Prime:

Flipkart Coding Questions with Solutions

1. Program for Finding Minimum in a Rotated Sorted Array Problem

You are given a sorted array that has been rotated between 1 and n times. For example:

  • If the array [1,2,3,4,5,6] is rotated 4 times, it becomes [3,4,5,6,1,2].
  • If rotated 6 times, it goes back to [1,2,3,4,5,6].

Your task is to find the smallest element in this rotated array. The elements in the array are unique.

While finding the minimum in O(n) time is easy, you need to write an algorithm that works in O(logn) time.

Constraints:

  • 1 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000

Solution with Binary Search Method

Use binary search to narrow down the search space by checking if the middle element lies in the rotated part, giving an O(logn) solution.

  • Time complexity: O(log 1)
  • Space complexity: O(1)

Code

2. Design Add and Search Words Data Structure

Design a data structure to store words and efficiently support word addition and searching, including flexible matching.

Implement the WordDictionary class with the following methods:

  • addWord(word): Adds the given word to the data structure, allowing it to be stored for future searches. This is useful for building a collection of words dynamically.
  • search(word): Searches for a word in the data structure. The search supports both exact matches and partial matches using the . character as a wildcard. The . can represent any letter, making the search versatile for patterns or incomplete words.

This structure is particularly useful for applications like pattern matching or word suggestions.

Explanation:

  • WordDictionary wordDictionary = new WordDictionary();
  • wordDictionary.addWord(“day”);
  • wordDictionary.addWord(“bay”);
  • wordDictionary.addWord(“may”);
  • wordDictionary.search(“say”); // return false
  • wordDictionary.search(“day”); // return true
  • wordDictionary.search(“.ay”); // return true
  • wordDictionary.search(“b..”); // return true

Constraints:

  • 1 <= word.length <= 20
  • word in addWord consists of lowercase English letters.
  • word in search consist of ‘.’ or lowercase English letters.

Solving with Brute Force Method

Words are stored in a list, and each search checks all words by iterating through them, including handling wildcards (.) character by character. This leads to a time complexity of O(m * n), where m is the number of words and n is the word length.

  • Time complexity: O(n) for addWord(), O(m∗n) for search().
  • Space complexity: O(m*n)

where m is the number of words added and n is the length of the string.

Code

Flipkart Coding Questions with Solutions

3. Maximum Depth of Binary Tree

You are given the root of a binary tree, and your task is to determine its depth.

Depth of a binary tree refers to the number of nodes present along the longest path starting from the root node down to the farthest leaf node. 

In simpler terms, it measures how deep the tree goes from the topmost node (the root) to the bottommost node (a leaf with no children). This depth represents the maximum number of steps needed to traverse the tree vertically.

Example:

Graph of Maximum Depth Array

Constraints:

  • 0 <= The number of nodes in the tree <= 100.
  • -100 <= Node.val <= 100

Solving with Iterative DFS(Stack) Method

This method uses a stack to simulate the depth-first traversal iteratively. Each node is paired with its depth and pushed onto the stack. As you process each node, you update the maximum depth by comparing the current depth of the node with the recorded value.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

4. Number of Connected Components In An Undirected Graph Problem

 Given an undirected graph with n nodes, an edges array is provided where edges[i] = [a, b] indicates an edge between node a and node b.

The nodes are numbered from 0 to n – 1. The task is to return the total number of connected components in the graph.

Constraints:

  • 1 <= n <= 100
  • 0 <= edges.length <= n * (n – 1) / 2

Solving with Disjoint Set Union (Rank | Size) method

DSU tracks the connected components using a union-find approach, where nodes are grouped into sets. Using union by rank or size ensures efficient merging of components, and the number of connected components is determined by the number of distinct sets.

  • Time complexity: O(V+(E∗α(V)))
  • Space complexity: O(V)

Where V is the number of vertices and E is the number of edges.

Code:

Flipkart Coding Questions

5. Maximum Product Subarray Problem

Given an integer array nums, find the subarray with the maximum product and return its value.

A sub array is a continuous, non-empty portion of the array.

You can assume the result will fit within a 32-bit integer.

Constraints:

  • 1 <= nums.length <= 1000
  • -10 <= nums[i] <= 10

Solving with Kadane’s Algorithm method

Modify Kadane’s algorithm to handle products by keeping track of both the maximum and minimum products at each index. This efficiently handles both positive and negative numbers.

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

6. Merging Triplets to Form a Target Triplet

The Merge Triplets to Form Target problem involves determining whether you can construct a specific triplet using a series of merging operations on given triplets.

Problem Description

Input

  1. triplets: A 2D list where each triplet is of the form [a, b, c].
  2. target: A triplet [x, y, z] that we aim to construct.

Operation

For two triplets triplets[i] = [ai, bi, ci] and triplets[j] = [aj, bj, cj], you can update triplets[j] as follows:
 triplets[j]=[max(ai,aj),max(bi,bj),max(ci,cj)]

Goal

Determine whether it is possible to make target an element of triplets after performing the allowed operations.

Constraints:

  • 1 <= triplets.length <= 1000
  • 1 <= ai, bi, ci, x, y, z <= 100

There are mainly two  approach to solve this problem – 

  1. Greedy
  2. Greedy (Optimal)

Flipkart Coding Questions and Answers

1. Greedy

  • Time complexity: O(n)
  • Space complexity: O(1)

2. Greedy (Optimal)

Time & Space Complexity
  • Time complexity: O(
  • Space complexity: O(1)

If you want to practice more for Flipkart Coding Assessment, you can visit our Coding Blogs that will surely help you to prepare for Flipkart SDE 1 Coding Assessment and Flipkart Technical Interviews. 

Practice Coding Questions:

Checkout PrepInsta Prime:

Faq's Related to Flipkart Coding Assessment

Answer:

The coding questions typically range from medium to hard difficulty, covering data structures, algorithms, and problem-solving logic relevant to real-world scenarios.

 

Answer:

Yes, Flipkart often includes problems based on Trees, Graphs, Binary Search Trees (BST), and Tries, so it’s important to have a solid grasp of these topics.

 

Answer:

Yes, HackerRank allows you to code in your preferred programming language, though proficiency in C++, Java, or Python is recommended due to better support and familiarity.

 

Uber Coding Questions and Answers

Uber Coding Questions with Solutions

Here on this page you will get Sample Uber coding questions and answers which will help you to prepare for Online Coding Assessment of Uber to hire freshers for SDE 1 Role.

Let you know that the Online Assessment will be conducted on CodeSignal Platform. After Application Process, candidates will be communicated through mail for Online Assessment on CodeSignal.

Sample Uber Coding Questions and Answers

Uber SDE 1 Profile Details

Role: Software Development Engineer 1 (SDE 1)
Work:

  • Develop, test, and maintain scalable software solutions.
  • Collaborate with teams to build high-performance applications.
  • Solve real-world engineering challenges using algorithms and data structures.

Tech Stack Required:

  • Programming Languages: Python, Java, C++, Go
  • Data Structures & Algorithms (DSA)
  • Databases: SQL, NoSQL (MongoDB, Cassandra)
  • Backend: Microservices, REST APIs
  • Frontend (if required): React, Angular
  • Cloud & DevOps: AWS, Kubernetes, Docker (preferred)

Checkout PrepInsta Prime:

Practice Coding Questions:

Further on this page you will get Sample Uber Coding Questions and Answers that will help you to prepare for Uber Online Coding Assessment on CodeSignal Platform.

Sample Uber Coding Questions with Solutions

Question 1: Finding Longest Repeating Character Replacement Problem

You are given a string s that contains only uppercase English letters and an integer k. Your task is to determine the length of the longest substring in s that can consist of just one distinct character after modifying the string.

You are allowed to make up to k replacements, where each replacement involves changing any character in the substring to another uppercase English letter.

The goal is to maximize the length of this uniform substring by carefully choosing which characters to replace while staying within the limit of k changes.

Constraints:

  • 1 <= s.length <= 1000
  • 0 <= k <= s.length

Solving Through Sliding Window Method

Maintain a sliding window and expand it to include more characters. If the number of characters to replace exceeds the limit, shrink the window from the left. Track the longest valid window during this process.

  • Time complexity: O(m*n)
  • Space complexity: O(m)

where n is the length of the string and m is the total number of unique characters in the string.

Code

Question 2: Serializing and Deserializing Binary Tree.

Create an algorithm to convert a binary tree into a string (serialization) and then reconstruct the same binary tree from that string (deserialization).

Serialization means converting a binary tree into a format that can be saved or sent to another system. Deserialization means converting that saved format back into the original binary tree.

Goal is to ensure that the binary tree can be serialized into a string and later deserialized back to its original structure without any loss of information. There are no specific rules for how you should implement this; the approach is up to you.

Example:

Output of Example 1 of Good Node

Constraints:

  • 0 <= The number of nodes in the tree <= 1000.
  • -1000 <= Node.val <= 1000

Solving Breadth First Search Method

In the BFS approach, the binary tree is serialized level by level using a queue to store node values. During deserialization, the data is processed sequentially to rebuild the tree by connecting child nodes level-wise.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

Question 3: N Queen Problem

The n-queens puzzle is about placing n queens on an n x n chessboard so that no two queens can attack each other.

Queens can attack in three ways: horizontally, vertically, and diagonally.

Your task is to find all possible ways to place the queens on the board, ensuring no two queens attack each other.

Each solution will show a unique board arrangement where ‘Q’ represents a queen and ‘.’ represents an empty square. The solutions can be returned in any order.

Example 1:

Example of N Queen problem

Constraints:

  • 1 <= n <= 8

Solving through Backtracking(Hash Set) Method

Here, we use hash sets to track the columns and diagonals already occupied by queens. These sets allow quick lookups to check if a cell is safe for placing a queen. The method reduces redundant checks and improves efficiency.

  • Time complexity: O(n!)
  • Space complexity: O(n^2)

Code

Question 4: Partition Equal Subset Sum

Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.

Example 1:

  • Input: nums = [1,2,3,5]
  • Output: false
  • Explanation: The array cannot be partitioned into equal sum subsets.

Constraints :

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 100

Code:

Question 5: Coin Change II: Counting Distinct Combinations

  • This problem involves finding the number of distinct combinations of coins that sum up to a given target amount.
  • It is a classic example of a Dynamic Programming (DP) problem, focusing on combinations rather than permutations.

Problem Description : Coin Change 2

You are given:

  1. An integer array coins where each element represents the denomination of a coin (e.g., 1, 5, 10, etc.).
  2. An integer amount representing the target sum.

Objective: Return the number of distinct combinations of coins that sum up to amount. If it’s impossible to reach the amount, return 0.

Problem Breakdown

  1. Input: 2D grid of non-negative integers.
  2. Objective: Find the length of the longest strictly increasing path.
  3. Movement: Can move to adjacent cells (up, down, left, right) but not diagonally.
  4. Constraints: Each move must go to a cell with a strictly greater value.
  5. Goal: Determine the longest path by efficiently exploring the grid.

Constraints: 

  • 1 <= coins[i] <= 1000
  • 1 <= coins.length <= 100
  • 0 <= amount <= 1000

Code:

These were some of most Important Uber Coding Questions and Answers. If you want to practice more you can visit our coding blogs to explore more….and also visit PrepInsta Prime Course.

Faq's Related to Uber Hiring Process

Question 1. What types of coding questions are asked in the Uber hiring process?

Answer:

Uber Coding Questions mainly includes topics like arrays, strings, dynamic programming, graphs, and recursion.

Question 2. Which programming languages are allowed for the Uber coding test?

Answer:

  • Uber allows candidates to code in multiple languages, mainly including C++, Java and Python.

Question 3. How can I prepare for Uber coding round?

Answer:

To prepare effectively:

Meesho Coding Questions and Answers

Meesho Coding Questions with Solutions

Here on this page you will get Sample Meesho coding questions and answers which will help you to prepare for Online Coding Assessment of Meesho to hire freshers for SDE Role.

Let you know that the Online Assessment will be conducted on Hackerearth Platform. After Resume Shortlisting Candidates will be communicated through mail for Online Assessment on Hackerearth.

meesho coding questions with solutions

Meesho Hiring 2025 Details

  • Role: SDE Trainee (6-month traineeship)

  • Stipend: ₹1,00,000 per month

  • Location: Bengaluru (Hybrid, 3 days in-office)

  • Eligibility: B.E/B.Tech/M.E/M.Tech (CSE, IT, ECE, EEE, E&I) & MCA (2024 & 2025 batch)

  • Selection Process:

    1. Application Submission
    2. HackerEarth Coding Test
    3. Technical & Hiring Manager Interview
    4. Offer Letter Rollout
  • Full-Time Opportunity: Based on performance, FTE offer with ₹20 LPA + benefits

  • Key Dates:

    • Apply by: 14th March 2025
    • Coding Test: 22nd March 2025
    • Interviews: 4th – 11th April 2025
    • Offer Rollout: 12th April 2025

Note: No active backlogs allowed. Candidates who participated in Meesho hiring in the last 6 months are not eligible.

Checkout PrepInsta Prime:

Practice Coding Questions:

Further on this page you will get Sample Meesho Coding Questions and Answers that will help you to prepare for Meesho Online Coding Assessment on Hackerearth Platform.

Sample Meesho Coding Questions with Solutions

Question 1: Program to check Valid Palindrome.

Given a string s, return true if it is a palindrome, otherwise return false.

A palindrome is a string that reads the same forward and backward. It is also case-insensitive and ignores all non-alphanumeric characters.

Explanation: After considering only alphanumerical characters we have “wasitacaroracatisaw”, which is a palindrome.

Constraints:

  • 1 <= s.length <= 1000
  • s is made up of only printable ASCII characters.
Solution:
Reverse String Method

This approach involves reversing the string representation of the array elements, sorting the reversed strings, and then checking for the longest consecutive sequence. However, it’s not commonly used for this problem as it focuses on string manipulation.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

Question 2: Buying and Selling Stocks Problem.

You are given an array prices, where each element prices[i] represents the price of PrepCoin on the i-th day.

Your task is to determine the maximum profit you can make by selecting one day to buy a PrepCoin and another day after it to sell.

If it’s not possible to make any profit (e.g., prices are decreasing every day), you should return 0. This means you can also choose not to make any transactions.

Explanation : No profitable transactions can be made, thus the max profit is 0.

Constraints:

  • 1 <= prices.length <= 100
  • 0 <= prices[i] <= 100
Solution:
Method 1: Two Pointers Method

Use a single pass with two variables to track the minimum price so far and the maximum profit, updating them as you traverse the array. This has a time complexity of O(n).

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

Method 2: Dynamic Programming Method

This method maintain a table or array to store intermediate results, such as the minimum price up to a given day and the maximum profit calculated so far, optimizing computation over multiple traversals. Time complexity is O(n).

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

Question 3: Program for Koko Eating Bananas Problem

You are given an array piles, where each element piles[i] represents the number of bananas in the i-th pile. You also have h hours to eat all the bananas. You can choose an eating rate of k bananas per hour. In each hour, you can eat up to k bananas from one pile.

If a pile has fewer than k bananas, you finish that pile but cannot switch to another pile during the same hour.

Your task is to find the minimum value of k that allows you to eat all the bananas within h hours.

Explanation: 

With an eating rate of 2, you can eat the bananas in 6 hours. With an eating rate of 1, you would need 10 hours to eat all the bananas (which exceeds h=9), thus the minimum eating rate is 2.

Constraints:

  • 1 <= piles.length <= 1,000
  • piles.length <= h <= 1,000,000
  • 1 <= piles[i] <= 1,000,000,000
Solution:
Using Binary Search Method

Use binary search to find the minimum eating speed by searching between 1 and the maximum pile size, checking the feasibility of each mid-speed.

  • Time complexity: O(n * log m)
  • Space complexity: O(1)

where n is the length of the input array piles and m is the maximum number of bananas in a pile.

Code

Sample Meesho Coding Questions

Question 4: Power Function (Pow(x, n))

Implement a function pow(x, n) that calculates x raised to the power n (i.e., x^n).

Constraints :

  • -100.0 < x < 100.0

  • -231 <= n <= 231-1

  • n is an integer.

  • Either x is not zero or n > 0.

  • -104 <= xn <= 104

Solution:

Question 5: Course Schedule Problem of Graphs.

You are given an array prerequisites, where each element prerequisites[i] = [a, b] means you must complete course b before taking course a.

For example, [0, 1] indicates that course 1 must be completed before course 0.

There are a total of numCourses, labeled from 0 to numCourses – 1. Return true if it is possible to complete all courses; otherwise, return false.

Explanation: First take course 1 (no prerequisites) and then take course 0.

Constraints :

  • 1 <= numCourses <= 1000
  • 0 <= prerequisites.length <= 1000
  • All prerequisite pairs are unique.
Solution:
Solving by Cycle Detection(DFS) Method

Treat the courses as a graph and use DFS to detect cycles. Maintain a visited set to track the current path during DFS. If a course is revisited in the same path, a cycle exists, making it impossible to complete all courses.

  • Time complexity: O(V + E)
  • Space complexity: O(V + E)

where V is the number of courses and E is the number of prerequisites.

Code

Question 6: Counting the Number of 1’s in Binary Representations of Numbers in a Range

Understanding binary numbers and efficiently processing them is a critical skill.

Common problem involves counting how many 1 bits are present in the binary representation of numbers within a given range.In this article, we will explore a solution to count the number of 1 bits in every number from 0 to n.

We need to count the number of 1 bits in the binary representations of numbers from 0 to 4. Let’s convert these numbers to binary:

  • 0 in binary: 0 → Number of 1 bits: 0
  • 1 in binary: 1 → Number of 1 bits: 1
  • 2 in binary: 10 → Number of 1 bits: 1
  • 3 in binary: 11 → Number of 1 bits: 2
  • 4 in binary: 100 → Number of 1 bits: 1

Solution:

Method 1. Bit Mask – I

Time & Space Complexity
  • Time complexity: O(1)
  • Space complexity: O(1)

Method 2. Built-In Function

Time & Space Complexity

  • Time complexity: O(1)
  • Space complexity: O(1)

Code

Meesho Coding Questions and Answers

Question 7: Print all combinations of balanced parentheses problem

You are given a positive integer n, representing the number of pairs of parentheses. Your task is to generate and return all possible combinations of well-formed (valid) parentheses strings that can be created using exactly n pairs.

A well-formed parentheses string maintains the correct order, meaning every opening parenthesis ( has a corresponding closing parenthesis ) that appears after it.

Explanation: You may return the answer in any order.

Constraints:

  • 1 <= n <= 7

Solution:

Using Dynamic Programming Method

Construct valid combinations using previously computed solutions for smaller values of n, combining them in different ways to form well-balanced parentheses for the current n.

  • Time complexity: O(4^n/(n)^1/2)
  • Space complexity: O(n)

Code

Question 8: LRU Cache Leetcode Problem

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

Implement the LRUCache class:

  1. LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
  2. int get(int key) Return the value of the key if the key exists, otherwise return -1.
  3. void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache.
  4. If the number of keys exceeds the capacity from this operation, evict the least recently used key.
  5. The functions get and put must each run in O(1) average time complexity.

Constraints :

  • 1 <= capacity <= 3000
  • 0 <= key <= 104
  • 0 <= value <= 105
  • At most 2 * 105 calls will be made to get and put.

Solution:

Question 9: Encode and Decode Strings Problem

Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings. Please implement encode and decode.

Constraints:

  • 0 <= strs.length < 100
  • 0 <= strs[i].length < 200
  • strs[i] contains only UTF-8 characters.

Solution:

Solving Encoding and Decoding Method

This method use a delimiter (like a special character or length-prefix) to encode strings, and split the encoded string using the same delimiter to decode. Simple but may face issues with delimiter conflicts.

  • Time complexity: O(m) for encode() and decode().
  • Space complexity: O(n) for encode() and decode().

where m is the sum of lengths of all the strings and n is the number of strings.

Code

Sample Meesho Coding Questions and Answers

Question 10: Kth Largest Element in an Array

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

Constraints :

  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

These were some of most Important Meesho Coding Questions and Answers. If you want to practice more you can visit our coding blogs to explore more….and also visit PrepInsta Prime Course.

FAQ's related to Meesho Coding Assessment

Question 1. What types of coding questions are asked in the Meesho hiring process?

Answer:

Meesho Coding Questions mainly includes topics like arrays, strings, dynamic programming, graphs, and recursion.

Problems can range from easy to hard, depending on the role you are applying for.

Question 2. Which programming languages are allowed for the meesho coding test?

Answer:

  • Meesho allows candidates to code in multiple languages, including Java, Python and JavaScript.
  • It is best to use one of these three languages that you are comfortable with and has built-in support for efficient data structures.

Question 3. How can I prepare for Meesho coding round?

Answer:

To prepare effectively:

  • Practice Coding Questions from our PrepInsta’s Coding Dashboard.
  • Focus on Time & Space Complexity of solutions.
  • Revise important algorithms like Binary Search, Two Pointers, and Graph Traversal.

Wipro Turbo Coding Questions

Wipro Turbo Coding Questions Asked

The Wipro Turbo hiring process is known for its rigorous assessment of candidates technical and problem-solving abilities. The Wipro Turbo Coding Questions, in particular, is designed to evaluate proficiency in various programming languages, including C, C++, Java, and Python.

Unlike the Wipro Elite NTH coding questions, which may focus on fundamental programming concepts, the Wipro Turbo coding assessments often present more complex and challenging problems.

Wipro Turbo Coding Questions asked in the interview
Total number of questions2 questions
Total Time Duration60 minutes
Type of TestNon-Adaptive
Mode ConductedOnline/Written
Negative MarkingNo

WIPRO TURBO Coding Questions and PROGRAMMING MODEL QUESTIONS

In this page you will find coding questions asked  during the off-campus placement of students, Wipro previous year questions:

  1. Wipro Turbo C Programming Questions for Off Campus
  2. Wipro Turbo Java Programming Questions for Off Campus
  3. Wipro Turbo C++ Programming Questions for Off Campus

Wipro Turbo Coding Questions 2025

Free Material

  • Program to calculate the GCD of two numbers –
  • Program to calculate the GCD of three numbers – 
  • Program to check if the given number is Prime or not – 
  • Program to Display the distinct elements of an array –
  • Program to Sort first half in ascending order and second half in descending order in an array –
  • Program for Matrix multiplication  –
  • Program to Remove vowels from an input string –
  • Program to Print Sum of all Odd Numbers present in a larger number –
  • Program to Print the Transpose of a matrix –
  • Program to Display the largest element in each row in a 2-D Array –
  • Program to Check the balance of Parenthesis –

Some Coding Questions for Practice

Note – These are some practice questions which are asked in Wipro on campus as well as Wipro off camous, so go through each questions and prepare well.

Question 1

Wipro’s client eBay wants to run a campaign on their website, which will have the following parameters, eBay wants that on certain x products, they want to calculate the final price, for each product on eBay there will be a stock unit parameter, this parameter will denote, how many items are their in their fulfillment center

Now, while these numbers if are positive means product x is available in the fulfillment center and if not than the product is not available and cannot be shipped to the customer 

Now the price on for each product varies based on the distance of the customer from the fulfillment center. Now, each product is in different fulfillment zone. Now, these values are 00’s kms for each centurion km. The price available would further increase by factor distance.

You’ve to find the maximum discount price for each product if the product can be shipped.

Following are the input/output parameters :

Input

  •  The first line of the input will contain number of products.
  • The second line will contain price for each of these products.
  • The third line contains shipping distance in 00’s kms
  • The fourth line contains SKU’s

Output

  • It will contain the final price for each deliverable item in SKU’s

Example :

Input:

  • 6
  • 87 103 229 41 8 86
  • 3 1 9 2 1 2
  • 7 -21 30 0 -4 -3

Output

  • 261 2061

Question : 2

(asked in Wipro On Campus, Sastra University, Aug, 2020)

Problem: in this first line you are required to take the value of m and n as the number of rows and columns of matrix, then you are required to take the input elements of array.
As an output you are required to print the sum of each row then the row having the maximum sum.
Test Case :
Input : 3 3
1 2 3
4 5 6
7 8 9
Output :
Row 1 : 6
Row 2 : 15
Row 3 : 24
Row 3 is having the maximum sum : 24

Question : 3

(asked in Wipro On Campus, PESIT Bangalore, Oct, 2019)

Problem: You are required to count the number of words in a sentence.
You are required to pass all the test cases

Test Cases :
Test Case : 1
Input : welcome to the world
Output : 4

Test Case : 2
Input : [space] say hello
Output : 2

Test Case : 3
Input : To get pass you need to study hard [space] [space]
Output : 8

Question : 4

(asked in Wipro On Campus, VIT University, Aug, 2019)

Problem: First of all you need to input a whole sentence in the string, then you need to enter the target
word.
As an output you need to find the number of times that particular target word is repeated in the
sentence.

Test Cases :

Test Case : 1
Input : welcome world to the new world
world
Output : 2

Test Case : 2
Input : working hard and working smart both are different ways of working
working
Output : 3

Question : 5

(asked in Wipro On Campus, MIET Meerut, Aug, 2019)

Problem Statement

You are required to implement the following function:
Int SumNumberDivisible(int m, int n);

The function accepts 2 positive integer ‘m’ and ‘n’ as its arguments.
You are required to calculate the sum of numbers divisible both by 3 and 5, between ‘m’ and ‘n’ both inclusive and return the same.

Note
0 < m <= n

Example
Input:
m : 12
n : 50
Output   90

Explanation:
The numbers divisible by both 3 and 5, between 12 and 50 both inclusive are
{15, 30, 45} and their sum is 90.

Sample Input

m : 100
n : 160

Sample Output

510

Question : 6

(asked in Wipro Off Campus)

Input
The first line of input consists of three space separated integers. Num, start and end representing the size of list [N], the starting value of the range and the ending value of the range respectively.
The second line of input consists N space separated integers representing the distances of the employee from the company.

Output
Print space separated integers representing the ID’s of the employee whose distance liew within the given range else return -1.

Example
Input
6 30 50
29 38 12 48 39 55

Output
1 3 4

Explanation :
There are 3 employees with id 1, 3, 4 whose distance from the office lies within the given range.

Question : 7

(asked in Wipro On Campus, IIIT Hyderabad, Aug, 2019)

Write a code for the following functions
Function 1 : sortArray
It’s function is to sort the passed array with a particular length, there are 2 parameters passed into it first is the length of array and next is the elements of list.
Function 2 : findMaxElement
It’s function is to get the 2 array with their own particular elements and length, and find the maximum element from both the array and print it.

Input
12
2 5 1 3 9 8 4 6 5 2 3 11
11
11 13 2 4 15 17 67 44 2 100 23

Output
100

Question 8

(asked in Wipro On Campus, HBTI Kanpur, Sep, 2019)

Problem: you are given a number, and you have to extract the key by finding the difference between the sum of the even and odd numbers of the input.

Test Case :

Input : 24319587

Output :  11

Explanation : odd terms : 3 + 1 + 9 + 5 + 7 = 25

                              even terms : 2 + 4 + 8 = 14

                              output : 11 (25-14)

Question 9

(asked in Wipro NLTH 2019)

Problem:  in this first line you are required to take the value of m and n as the number of rows and columns of matrix, then you are required to take the input elements of array.

As an output you are required to print the sum of each row then the row having the maximum sum.

Test Case :

Input : 3 3

               1 2 3

               4 5 6

               7 8 9

Output :  

               Row 1 : 6
               Row 2 : 15
               Row 3 : 24

               Row 3 is having the maximum sum : 24

Wipro Turbo Coding Questions

Question 10

(asked in Wipro NLTH 2019)

Problem:  in this first line you are required to take the input that set the number of elements to be inserted, the next line takes the elements as input.

You are required to print the sum of maximum and minimum element of the list

Test Case :

Input : 6

               55 87 46 21 34 79

Output :  

               108 

Explanation : 

               21 + 87 = 108

Question 11

(asked in Wipro NLTH 2019)

Problem:  in this first line you are required to take the input of an integer number, and in the second line you are required to input the target element 

You are required to print the number of time target element occured in the integer

Test Case :

Input : 734139

               3

Output :  

               2 

Explanation : 

               3 occured 2 times in the integer.

Some more Wipro Turbo Coding Questions for practice

TCS SMART VERBAL

Wipro Turbo Coding  Question 1

TCS SMART VERBAL

Wipro Turbo Coding  Question 2

TCS SMART VERBAL

Wipro Turbo Coding  Question 3

Wipro Turbo Coding Question 4

ibm english syllabus

Wipro Turbo Coding Question 5

ibm english syllabus

Wipro Turbo Coding Question 6

ibm verbal syllabus

Wipro Turbo Coding Question 7

Wipro Turbo Coding Question 8

ibm english syllabus

Wipro Turbo Coding Question 9

ibm english syllabus

Wipro Turbo Coding Question 10

ibm verbal syllabus

Wipro Turbo Coding Question 11

Wipro Turbo Coding Question 12

ibm english syllabus

Wipro Turbo Coding Question 13

ibm english syllabus

Wipro Turbo Coding Question 14

ibm verbal syllabus

Wipro Turbo Coding Question 15

Wipro Turbo Coding Question 16

Wipro Turbo Coding Question 17

Wipro Turbo Coding Question 18

ibm english questions and answers

Wipro Turbo Coding Question 19

ibm english questions and answers

Wipro Turbo Coding Question 20

Deloitte NLA Coding Questions and Answers

Deloitte NLA Coding Questions with Solutions

 On the Deloitte NLA Coding Questions and Answers page, you will find out all the details related to the Hiring process of Deloitte including Coding Questions asked in NLA ( National Level Assessment ) and Technical Interview, Job Profile, Salary, Job Location, and other related details.

Deloitte NLA Coding Question with solution

About Deloitte

Deloitte, formally known as Deloitte Touche Tohmatsu Limited is a leading global services provider company. They provide services in consulting, financial advisory, tax management, risk management, audit, and assurance.

Deloitte is also having a Subsidiary, Deloitte US – India Consulting, which works under the Deloitte US Organization providing the same services as Deloitte US Organization gives.

About Deloitte NLA Recruitment Process

This Hiring process of Deloiite National Level Assessment consists of following steps :

  1. Online Assessment [ Aptitude, Verbal and Technical Based ]
  2. Technical and HR Interview

Note – We have a dedicated page for Deloitte NLA Coding Questions and Answers, but if you want exact “What type of questions asked in Deloitte NLA Coding Round”, scroll down and fulfill your dream 🙂

We have mentioned further details of Deloitte NLA Recruitment Process in following Tabular Form for a particular Job Profile

PointsRelated Informations
Position :Analyst Trainee
Course :
  • B.Tech – CSE, IT, ECE, EEE & M.C.A.
  • Eligible Batch – 2025
Eligibility Criteria / Academic Qualification Required :Minimum 60% or equivalent CGPA of 6.5 and above
Cost to Company (CTC)Rs 4,00,000 /- P.A
Selection Process :
  1. Applying on Official Website
  2. Online National Level Assessment (NLA)
  3. Technical & HR Interview

Pattern of  Deloitte NLA Recruitment Exam :

Deloitte National Level Assessment has a 90-minute time limit and is divided into 4 sections, which are mentioned below :

Topics Number of Questions
Language Skills (English) 10 MCQs + 3 FUBs

General Aptitude

 12 Reasoning + 10 Quants
Technical  MCQs 30 Questions
Coding Questions 2  Questions 

Deloitte NLA Coding Questions and Answers

Question 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

Question 2

Problem 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”.

Constraints-

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

Question 3

You are given a function,
int findCount(int arr[], int length, int num, int diff);

The function accepts an integer array ‘arr’, its length and two integer variables ‘num’ and ‘diff’. Implement this function to find and return the number of elements of ‘arr’ having an absolute difference of less than or equal to ‘diff’ with ‘num’.
Note: In case there is no element in ‘arr’ whose absolute difference with ‘num’ is less than or equal to ‘diff’, return -1.

Example:
Input:

  • arr: 12 3 14 56 77 13
  • num: 13
  • diff: 2

Output:
3

Explanation:
Elements of ‘arr’ having absolute difference of less than or equal to ‘diff’ i.e. 2 with ‘num’ i.e. 13 are 12, 13 and 14.

Question 4

Implement the following Function 

def differenceofSum(n. m)

The function accepts two integers n, m as arguments Find the sum of all numbers in range from 1 to m(both inclusive) that are not divisible by n. Return difference between sum of integers not divisible by n with sum of numbers divisible by n.

Assumption:

  • n>0 and m>0
  • Sum lies between integral range

Example

Input
n:4
m:20
Output
90

Explanation

  • Sum of numbers divisible by 4 are 4 + 8 + 12 + 16 + 20 = 60
  • Sum of numbers not divisible by 4 are 1 +2 + 3 + 5 + 6 + 7 + 9 + 10 + 11 + 13 + 14 + 15 + 17 + 18 + 19 = 150
  • Difference 150 – 60 = 90

Sample Input
n:3
m:10
Sample Output
19

 Question 5

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.

FAQs related to Deloitte NLA Coding Questions

Question 1: What kind of roles are available at Deloitte in India?

Deloitte offers a variety of roles across different domains like Audit, Consulting, Financial Advisory, Risk advisory, Tax and related services.

Question 2: Does Deloitte asks coding questions in there Recruitment Process?

Yes, Deloitte asks coding questions in there National Level Assessment and Technical Interview.

Question 3: Is Registration Process is still going on?

Yes, The registration process is still going on, You can apply directly via Deloitte Registration Page.

TCS NQT Coding Questions and Answers 2025

TCS NQT Coding Questions with Answers for Freshers

TCS NQT Coding Questions

TCS NQT Coding Questions are asked in TCS NQT Advanced Coding Round. This round will  be of high difficulty. Below you will find questions based on the current updated pattern on TCS NQT 2025. You must prepare for the upcoming TCS NQT Advanced Coding Round from this page in order to ace your exam.

  • C / C++
  • Java
  • Python
  • Perl

Details regarding TCS NQT Coding Round

 

DetailsCoding Round
Number of Questions3 questions
Time Limit90 mins

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

TCS NQT Coding Question – September Day 1 – Slot 1

Problem 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”.

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.

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.

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

 

TCS NQT Coding Question Day 2 Slot 1 – Question 2

A supermarket maintains a pricing format for all its products. A value N is printed on each product. When the scanner reads the value N on the item, the product of all the digits in the value N is the price of the item. The task here is to design the software such that given the code of any item N the product (multiplication) of all the digits of value should be computed(price).

Example 1:

Input :

5244 -> Value of N

Output :
160 -> Price 

Explanation:

From the input above 

Product of the digits 5,2,4,4

5*2*4*4= 160

Hence, output is 160.

TCS NQT Coding Question Day 3 Slot 2 – Question 1

A furnishing company is manufacturing a new collection of curtains. The curtains are of two colors aqua(a) and black (b). The curtains color is represented as a string(str) consisting of a’s and b’s of length N. Then, they are packed (substring) into L number of curtains in each box. The box with the maximum number of ‘aqua’ (a) color curtains is labeled. The task here is to find the number of ‘aqua’ color curtains in the labeled box.

Note :

If ‘L’ is not a multiple of N, the remaining number of curtains should be considered as a substring too. In simple words, after dividing the curtains in sets of ‘L’, any curtains left will be another set(refer example 1)

Example 1:

Input :

bbbaaababa -> Value of str

3    -> Value of L

Output:

3   -> Maximum number of a’s

Explanation:

From the input given above.

Dividing the string into sets of 3 characters each 

Set 1: {b,b,b}

Set 2: {a,a,a}

Set 3: {b,a,b}

Set 4: {a} -> leftover characters also as taken as another set

Among all the sets, Set 2 has more number of a’s. The number of a’s in set 2 is 3.

Hence, the output is 3.

Example 2:

Input :

abbbaabbb -> Value of str

5   -> Value of L

Output:

2   -> Maximum number of a’s

Explanation:

From the input given above,

Dividing the string into sets of 5 characters each.

Set 1: {a,b,b,b,b}

Set 2: {a,a,b,b,b}

Among both the sets, set 2 has more number of a’s. The number of a’s in set 2 is 2.

Hence, the output is 2.

Constraints:

1<=L<=10

1<=N<=50

The input format for testing 

The candidate has to write the code to accept two inputs separated by a new line.

First input- Accept string that contains character a and b only

Second input- Accept value for N(Positive integer number)

The output  format for testing

The output should be a positive integer number of print the message(if any) given in the problem statement.(Check the output in Example 1, Example 2).

TCS NQT Coding Question Day 3 Slot 2 – Question 2

An international round table conference will be held in india. Presidents from all over the world representing their respective countries will be attending the conference. The task is to find the possible number of ways(P) to make the N members sit around the circular table such that.

The president and prime minister of India will always sit next to each other.

Example 1:

Input :

4   -> Value of N(No. of members)

Output : 

12  -> Possible ways of seating the members

Explanation:

2  members should always be next to each other. 

So, 2 members can be in 2!ways

Rest of the members can be arranged in (4-1)! ways.(1 is subtracted because the previously selected two members will be considered as single members now).

So total possible ways 4 members can be seated around the circular table 2*6= 12.

Hence, output is 12.

Example 2:

Input:

10  -> Value of N(No. of members)

Output :

725760 -> Possible ways of seating the members 

Explanation:

2 members should always be next to each other.

So, 2 members can be in 2! ways 

Rest of the members can be arranged in (10-1)! Ways. (1 is subtracted because the previously selected two members will be considered as a single member now).

So, total possible ways 10 members can be seated around a round table is 

2*362880 = 725760 ways.

Hence, output is 725760.

The input format for testing

The candidate has to write the code to accept one input 

First input – Accept value of number of N(Positive integer number)

The output format for testing 

The output should be a positive integer number or print the message(if any) given in the problem statement(Check the output in example 1, example2)

Constraints :

2<=N<=50

TCS NQT Coding Question Day 4 Slot 1 – Question 1

Problem Statement

An intelligence agency has received reports about some threats. The reports consist of numbers in a mysterious method. There is a number “N” and another number “R”. Those numbers are studied thoroughly and it is concluded that all digits of the number ‘N’ are summed up and this action is performed ‘R’ number of times. The resultant is also a single digit that is yet to be deciphered. The task here is to find the single-digit sum of the given number ‘N’ by repeating the action ‘R’ number of times.

If the value of ‘R’ is 0, print the output as ‘0’.

Example 1:

Input :

99 -> Value of N

3  -> Value of R

Output :

9  -> Possible ways to fill the cistern.

Explanation:

Here, the number N=99

  1. Sum of the digits N: 9+9 = 18
  2. Repeat step 2 ‘R’ times i.e. 3 tims  (9+9)+(9+9)+(9+9) = 18+18+18 =54
  3. Add digits of 54 as we need a single digit 5+4

Hence , the output is 9.

Example 2:

Input :

1234   -> Value of N

2      -> Value of R

Output :

2  -> Possible ways to fill the cistern

Explanation:

Here, the number N=1234

  1. Sum of the digits of N: 1+2+3+4 =10
  2. Repeat step 2 ‘R’ times i.e. 2 times  (1+2+3+4)+(1+2+3+4)= 10+10=20
  3. Add digits of 20 as we need a single digit. 2+0=2

Hence, the output is 2.

Constraints:

0<N<=1000

0<=R<=50

The Input format for testing 

The candidate has to write the code to accept 2 input(s)

First input- Accept value for N (positive integer number)

Second input: Accept value for R(Positive integer number)

The output format for testing 

The output should be a positive integer number or print the message (if any) given in the problem statement. (Check the output in Example 1, Example 2).

TCS NQT Coding Question Day 4 Slot 1 – Question 2

Problem Statement

Particulate matters are the biggest contributors to Delhi pollution. The main reason behind the increase in the concentration of PMs include vehicle emission by applying Odd Even concept for all types of vehicles. The vehicles with the odd last digit in the registration number will be allowed on roads on odd dates and those with even last digit will on even dates.

Given an integer array a[], contains the last digit of the registration number of N vehicles traveling on date D(a positive integer). The task is to calculate the total fine collected by the traffic police department from the vehicles violating the rules.

Note : For violating the rule, vehicles would be fined as X Rs.

Example 1:

Input :

4 -> Value of N

{5,2,3,7} -> a[], Elements a[0] to a[N-1], during input each element is separated by a new line

12 -> Value of D, i.e. date 

200 -> Value of x i.e. fine

Output :

600  -> total fine collected 

Explanation:

Date D=12 means , only an even number of vehicles are allowed. 

Find will be collected from 5,3 and 7 with an amount of 200 each.

Hence, the output = 600.

Example 2:

Input :

5   -> Value of N 

{2,5,1,6,8}  -> a[], elements a[0] to a[N-1], during input each element is separated by new line

3 -> Value of D i.e. date 

300 -> Value of X i.e. fine 

Output :

900  -> total fine collected 

Explanation:

Date D=3 means only odd number vehicles with are allowed.

Find will be collected from 2,6 and 8 with an amount of 300 each.

Hence, the output = 900 

Constraints:

  • 0<N<=100
  • 1<=a[i]<=9
  • 1<=D <=30
  • 100<=x<=5000 

The input format for testing 

The candidate has to write the code to accept 4 input(s).

First input – Accept for N(Positive integer) values (a[]), where each value is separated by a new line.

Third input – Accept value for D(Positive integer)

Fourth input – Accept value for X(Positive integer )

The output format for testing 

The output should be a positive integer number (Check the output in Example 1, Example e) if no fine is collected then print ”0”.

24 comments on “TCS NQT Coding Questions and Answers 2025”


  • sundareshwaran

    import java.util.*;
    class Main{
    public static void main(String[] args){
    Scanner sc=new Scanner(System.in);
    int t=0;
    int n=sc.nextInt();
    int arr[]=new int[n];
    for(int i=0;i<n;i++){
    arr[i]=sc.nextInt();
    }

    int c=1;
    int d=sc.nextInt();
    int f=sc.nextInt();
    for(int i=0;i<n;i++){
    if(d%2==0){
    if(arr[i]%2!=0){
    t=f*c;
    c++;
    }
    }
    else{
    if(arr[i]%2==0){
    t=f*c;
    c++;
    }
    }
    }System.out.println(t);
    }
    }


  • mallasatish681

    n=int(input())
    ar=list(map(int,input().split()))
    date=int(input())
    fine=int(input())
    e,o=0,0
    for i in range(n):
    if ar[i]%2==0:
    e=e+1
    else:
    o=o+1
    if date%2==0:
    if o==0:
    print(“0”)
    else:
    print(o*fine)
    else:
    if e==0:
    print(“0”)
    else:
    print(e*fine)


  • patilmayur4102002

    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println(“ENter how many people cross road”);
    int n = sc.nextInt();
    int arr[]=new int[n];
    for(int i=0;i<arr.length;i++) {
    arr[i]=sc.nextInt();
    }
    System.out.println("Enter date");
    int date= sc .nextInt();
    System.out.println("Enter fine amount");
    int fine= sc.nextInt();
    int totalfine=0;
    for(int i=0;i<arr.length;i++) {
    if((date%2==0 && arr[i]%2!=0) ||(date%2!=0 && arr[i]%2==0)) {
    totalfine +=fine;
    }
    }
    System.out.println(totalfine);
    }


  • chetansmankar360

    TCS NQT Coding Question Day 4 Slot 1 – Question 2

    import java.util.Scanner;

    public class TotalFine {
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();

    int arr[] = new int[n];
    for(int i=0; i<arr.length; i++) {
    arr[i] = sc.nextInt();
    }

    int d = sc.nextInt();
    int f = sc.nextInt();
    sc.close();

    boolean isEvenDate = d%2 == 0;
    int totalFine = 0;
    for(int x:arr) {
    if(x%2 != 0 && isEvenDate || x%2 == 0 && !isEvenDate) {
    totalFine += f;
    }
    }

    System.out.println(totalFine);
    }
    }


  • dharaneesh27112003

    def count_sundays(start_day, n):
    # Mapping of days to their respective indices
    day_map = {
    ‘sun’: 0,
    ‘mon’: 1,
    ‘tue’: 2,
    ‘wed’: 3,
    ‘thu’: 4,
    ‘fri’: 5,
    ‘sat’: 6
    }
    startindex=day_map[start_day]

    first_sunday=7-startindex
    if first_sunday>n:
    return 0
    else:
    rem=n-first_sunday
    return (1+(rem//7))

    start_day = ‘sat’ # Starting day of the month
    n_days = 30 # Number of days from the start of the month
    result = count_sundays(start_day, n_days)
    print(result)


  • Yashsvi Chawhan

    n = int(input())
    reg_num = []
    for _ in range(n):
    reg_num.append(int(input()))
    d = int(input())
    s = int(input())

    total = 0
    for num in reg_num:
    if (d % 2 == 0 and num % 2 != 0) or (d % 2 != 0 and num % 2 == 0):
    total += s
    if total != 0 :
    print(total)
    else:
    print(“0”)


  • Niraimathi

    import java.util.*;

    public class main {

    public static void main(String[] args) {
    Scanner s= new Scanner(System.in);
    System.out.print(“enter the number of arrays: “);
    int n= s.nextInt();
    int []arr=new int[n];
    for(int i=0;i<arr.length;i++){
    arr[i]=s.nextInt();
    } int x=300;
    int d=3;
    int count=0;
    if(d%2!=0){

    for(int j=0;j<arr.length;j++){
    if(j%2==0){
    count++;
    }
    }
    }else{
    for(int j=0;j<arr.length;j++){
    if(j%2!=0){
    count++;
    }
    }
    }

    System.out.print(count*x);
    }
    }


  • Sanjay.S

    TCS NQT Coding Question Day 4 Slot 1 – Question 2

    Initial=list(map(int,input().split()))
    Date=int(input(“Enter the date:”))
    fine1=int(input(“Enter the Fine Amount:”))
    fine=0
    if Date%2==0:
    for i in Initial:
    if i==1:
    fine+=0
    elif i%2!=0 :
    fine+=fine1
    else:
    for i in Initial:
    if i==1:
    fine+=0
    elif i%2==0 :
    fine+=fine1
    print(“The Total Fine amount will be:”,fine)


  • Chandu

    Day 2 slot 1-Question 2
    n=int(input(“Enter number”))
    a=[]
    for i in range(n):
    a.append(int(input()))
    d=int(input(“Enter date”))
    fine=int(input(“Enter fine”))
    count=0
    if d%2==0:
    temp=1
    else:
    temp=0
    for i in a:
    if temp==1:
    if i%2!=0:
    count+=fine
    else:
    if i%2==0:
    count+=fine
    print(count)


  • Tri

    Day 4 slot 1 question 1
    N = int(input())
    R = int(input())
    def sum_of_digits(num):
    sum_of_digits = 0

    for i in str(num):
    sum_of_digits += int(i)
    return sum_of_digits
    num_sum = sum_of_digits(N)
    result = num_sum * R
    result_sum = sum_of_digits(result)
    final_result = result_sum if R!=0 else 0
    print(final_result)

HCL Coding Questions and Answers

HCL Practice Coding Questions

As coding turns out to be the most crucial section of HCL recruitment examination, we believe that having a mindset for HCL Coding  Questions & Answers is important. As the number of questions is only 2 but the time allotted is only 20 mins so it becomes very hard to pass all the test cases. Hence, this makes it obvious to understand the pattern of questions asked in HCL Placement Paper. This page will help you to know the solution of some coding questions.

HCL Coding Questions and Answers 2024

About HCL Exam Pattern 2025

TopicsNumber of QuestionsTimeDifficulty
Numerical Ability1515 minsMedium
Verbal Ability1515 minsMedium
Reasoning Ability1515 minsMedium
Computer Programming3030 minsHigh
Coding220 minsHigh

HCL Coding Questions : Detailed Analysis

Find the complete analysis for HCL Coding Section below in the tabular format for better understanding.

HCL Section No. of questions Total Time
MCQ 30 30 mins
Coding Challenge 2 20 mins

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Some facts about Eligibility Criteria:-

The eligibility criteria for HCL is given below in the tabulated format.
HCLRequirements
QualificationB.Tech
Eligible stream(CSE,IT,ECE,EN,EI, ME)
Percentage Criteria75% throughout academics (10th, 12th / Diploma & UG)
BacklogNo Active Backlog
Service AgreementProbation period for selected SE/GET will be of 12 Months.

Practice Coding Question for HCL

Question 1 :

PrepInsta Name : Move Hash to Front

Problem Statement : You have write a function that accepts, a string which length is “len”, the string has some “#”, in it you have to move all the hashes to the front of the string and return the whole string back and
print it.

char* moveHash(char str[],int n);

  • Example :

    Sample Test Case

  • Input:
    Move#Hash#to#Front
  • Output:
    ###MoveHashtoFront

Question 2 :

PrepInsta Name : Borrow Number

Problem statement : You have two numbers number1 and number2, your job is to check the number of borrow operations needed for subtraction of number1 from number2. If the subtraction is not possible
then return the string not possible.

Example :

  • 754
    658
  • Answer :
    2
    654
    666
  • Answer:
    Not possible

Question 3 :

PrepInsta Name : Capitalize/Decapitalize

Problem statement : You’re given a function that accepts the following, a string1, its length and a character c. Your job is to replace all the occurrences of character c in string1 and capitalize it or decapitalize it based on the character c.

Question 4 :

Problem statement : You’re given a string where multiple characters are repeated consecutively. You’re supposed to reduce the size of this string using mathematical logic given as in the example below :

Question 5 :

PrepInsta Name : Spiral Matrix

Problem statement : You will be given a 2d matrix. Write the code to traverse the matrix in a spiral format. Check the input and output for better understanding.

Example :

Input :

5 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20

Output :

1 2 3 4 8 12 16 20 19 18 17 13 9 5 6 7 11 15 12 14 10

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Amazon Coding Questions

Amazon Coding Questions and Answers

On this page, the 2024  Amazon Coding Questions and Answers are discussed. One of the most crucial rounds for landing a job at Amazon is the coding round.

You can use this section to analyse the level of complexity of the Amazon problem. Understanding the level of complexity and question format for the coding phase is made easier by practising Amazon code questions and answers.

The Amazon Coding Round questions and their solutions in different languages can be found below. For a good grade, you must be prepared for the Amazon code problems.

Coding Test Format

The Amazon coding round is an important step in the interview process.

It assesses a candidate’s problem-solving skills and ability to apply algorithms and data structures to solve coding problems.

  • Coding round contains 3 questions that will have to be attended in 3 hours.
  • Each questions have different difficulty level.
  • There is one Easy problem based on Algorithm , Aptitude and Data structures.
  • One of the problem is of Medium level and that problem is based on Greedy Algorithm.
  • One is of Hard difficulty level, and usually based on Dynamic Programming.
No Of QuestionsMarks per question
Question 120
Question 230
Question 350

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Question 1

Problem Statement: Check if strings are rotations of each other or not
Given two strings s1 and s2. The task is to check if s2 is a rotated version of the string s1. The characters in the strings are in lowercase.

Test Case 1:

Input:
mightandmagic
andmagicmigth

Output:
0

Explanation:
Here with any amount of rotation s2 can’t be obtained by s1.

Your Task:
The task is to complete the function areRotations() which checks if the two strings are rotations of each other. The function returns true if string 1 can be obtained by rotating string 2, else it returns false.

  • Expected Time Complexity: O(N).
  • Expected Space Complexity: O(N).
  • Note: N = |s1|.

Constraints:

  • 1 <= |s1|, |s2| <= 107

Question 2

Problem Statement:

Jarvis is weak in computing palindromes for Alphanumeric characters.While Ironman is busy fighting Thanos, he needs to activate sonic punch but Jarvis is stuck in computing palindromes.You are given a string S containing alphanumeric characters. Find out whether the string is a palindrome or not. If you are unable to solve it then it may result in the death of Iron Man.

Test Case 1:-

Input:
S = “I am :IronnorI Ma, i”

Output:
YES

Explanation:
Ignore all the symbols and whitespaces S = “IamIronnorIMai”. Now, Check for palindrome ignoring uppercase and lowercase English letter.

Test Case 2:-

Input:
S = Ab?/Ba

Output:
YES

Explanation:
Here with any amount of rotation s2 can’t be obtained by s1.

Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function saveIronman() that takes an string (ch), and return the true if the string is a palindrome and false if the string is not a palindrome. The driver code takes care of the printing.

  • Expected Time Complexity: O(N).
  • Expected Space Complexity: O(1).

Note: N = |s1|.

Constraints:

  • 1 ≤ |S| ≤ 100000

Note: Consider alphabets and numbers only for palindrome check. Ignore symbols and whitespaces.

Question 3

Problem Statement:

Given a binary tree, print the bottom view from left to right.

A node is included in bottom view if it can be seen when we look at the tree from bottom.

                    20
                   
/ \
                
8   22
                 /   \   
\
                5  3
  25
                /   \ 

              10
14

For the above tree, the bottom view is 5 10 3 14 25.

If there are multiple bottom-most nodes for a horizontal distance from root, then print the later one in level traversal. For example, in the below diagram, 3 and 4 are both the bottommost nodes at horizontal distance 0, we need to print 4.

                   20
                  
/ \
               
8   22
            
/   \     /   \
          
5  3  4   25
           
  /        \ 
           10          14

For the above tree the output should be 5 10 4 14 25.

Example 1:
Input:

       1
     /   \
    3     2

Output: 3 1 2

Explanation:
First case represents a tree with 3 nodes and 2 edges where root is 1, left child of 1 is 3 and right child of 1 is 2.

Example 2:
Input:

         10
       /    \
     20    30
     /  \
  40   60

Output: 40 20 60 30

Your Task:
This is a functional problem, you don’t need to care about input, just complete the function bottomView() which takes the root node of the tree as input and returns an array containing the bottom view of the given tree.

  • Expected Time Complexity: O(N).
  • Expected Auxiliary Space: O(N).

Constraints:

  • 1 <= Number of nodes <= 105
  • 1 <= Data of a node <= 105

Question 4

An expression is called the postfix expression if the operator appears in the expression after the operands.

Example :

Infix expression: A + B  *  C – D 

Postfix expression:  A B + C D – *

Given a postfix expression, the task is to evaluate the expression. The answer could be very large, output your answer modulo (10^9+7). Also, use modular division when required.

Note:

  • Operators will only include the basic arithmetic operators like ‘*’, ‘/’, ‘+’, and ‘-‘.
  • The operand can contain multiple digits. 
  • The operators and operands will have space as a separator between them.
  • There won’t be any brackets in the postfix expression.

Input Format:

  • The first line of input contains an integer ‘T’ denoting the number of test cases.
  • The next ‘T’ lines represent the ‘T’ test cases.
  • The first and only line of each test case contains a postfix expression.

Output Format:

  • The first line of input contains an integer ‘T’ denoting the number of test cases.
  • For each test case, print an integer obtained by evaluating the given postfix expression.

Note:

You are not required to print the expected output; it has already been taken care of, Just implement the function.

Constraints
  • 1 <= T <= 100
  • 1 <= N <= 10^3
  • 1 <= NUM <= 100

Where ‘N’ denotes the length of postfix expression and ‘NUM’ denotes the operand.

Time Limit: 1 sec

Sample input 1

2
2 3 1 * + 9 –
1 2 3 + * 8 –

Explanation of sample input 1:

Sample output 1

-4
-3

 

Test case 1:

2 3 1 * + 9 –
– : ( ) – ( )
9 : ( ) – (9)
+ : ( ( ) + ( ) ) – (9)
‘*’:  ( ( ) + ( ( ) * ( ) ) ) – (9)
1 : ( ( ) + ( ( ) * (1) ) ) – (9)
3 : ( ( ) + ( (3) * (1) ) ) – (9)
2 : ( (2) + ( (3) * (1) ) ) – (9) 

Result = (2 + 3) – 9 = 5 – 9 = -4

Test case 2:

1 2 3 + * 8 –
 – : ( ) – ( )
8 : ( ) – (8)
* : ( ( ) * ( ) ) – (8)
+ : ( ( ) * ( ( ) + ( ) ) ) – (8)
3 : ( ( ) * ( ( ) + (3) ) ) – (8)
2 : ( ( ) * ( (2) + (3) ) ) – (8)
1 : ( (1) * ( (2) + (3) ) ) – (8) 

Result = (1 * 5) – 8 = 5 – 8 = -3

Sample input 2

1
100 200 + 2 / 5 * 7 +

Explanation of sample input 2:

100 + 200 = 300
300 / 2 = 150
150 * 5 = 750
750 + 7 = 757

Sample output 2

757

 Question 5

Asked in Infosys Placment Paper – Feb 2022

Problem Statement :

You are given a binary tree, the task is to find out the length of the longest path which contains nodes with the exact same value. It is not necessary for the path to pass through the root of the binary tree.Between two nodes, the length of the path can be defined as the number of edges contained between them.

For example, consider the following binary tree:

                    7

                /     \

               7         7

            /   \         \

           8     3         7

For the above tree, the length of the longest path where each node in the path has the same value is 3 and path is 7 -> 7 -> 7 -> 7

   Input format:

  • The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.
  • The only line of each test case contains elements in the level order form. The line consists of values of nodes separated by a single space. In case a node is null, we take -1 on its place.
  • For example, the input for the tree depicted in the below image would be:

1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1

Explanation:

  • Level 1:
    • The root node of the tree is 1
  • Level 2:
    • Left child of 1 = 2
    • Right child of 1 = 3
  • Level 3:
    • Left child of 2 = 4
    • Right child of 2 = null (-1)
    • Left child of 3 = 5
    • Right child of 3 = 6
  • Level 4:
    • Left child of 4 = null (-1)
    • Right child of 4 = 7
    • Left child of 5 = null (-1)
    • Right child of 5 = null (-1)
    • Left child of 6 = null (-1)
    • Right child of 6 = null (-1)
  • Level 5:
    • Left child of 7 = null (-1)
    • Right child of 7 = null (-1)

The first not-null node(of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.

The input ends when all nodes at the last level are null(-1).

Note:

The above format was just to provide clarity on how the input is formed for a given tree. The sequence will be put together in a single line separated by a single space. Hence, for the above-depicted tree, the input will be given as:

1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1

Output Format:
For each test case, a single integer denoting the length of the longest path where each node in the path has the same value is printed. The output for each test case is to be printed on a separate line.

Note:

You do not need to print anything; it has already been taken care of. Just implement the given function.

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 3000
  • -10^9 <= data <= 10^9 and data != -1

 Where ‘T’ is the number of test cases, ‘N’ is the total number of nodes in the binary tree, and “data” is the value of the binary tree node.

Time Limit: 1sec

Sample Input 1:

2
7 7 7 1 1 -1 7 -1 -1 -1 -1 -1 -1
10 3 4 3 3 -1 5 -1 -1 -1 -1 -1 -1

Sample Output 1:

3
2

Sample Input 2:

2
1 4 5 4 4 -1 5 -1 -1 -1 -1 -1 -1
5 4 5 1 1 -1 5 -1 -1 -1 -1 -1 -1

Sample Output 2:

2
2

 Explanation of Sample Input 1:
            7
           / \
          7   7
         / \   \
        1  1    7
For the first test case, the length of the longest path where each node in the path has the same value is 3 and path is 7 -> 7 -> 7 -> 7.

          10
           / \
         3   4
         / \   \
        3  3    5
For the second test case, the length of the longest path where each node in the path has the same value is 2 and path is 3 -> 3 -> 3.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription