
Nagarro


80+ Nagarro Interview Questions and Answers for Freshers
Q1. Crazy Numbers Pattern Challenge
Ninja enjoys arranging numbers in a sequence. He plans to arrange them in 'N' rows such that:
- The first row contains 1 number.
- The second row contains 2 numbers.
- The third row c...read more
Arrange numbers in a sequence in 'N' rows with increasing order and repeating after 9.
Iterate through each test case and for each row, print numbers in increasing order with a loop.
Keep track of the current number to print and reset to 1 after reaching 9.
Handle formatting to align numbers correctly in each row.
Ensure to print the correct number of rows based on the input 'N'.
Q2. Ninja and the New Year Guests Problem
Ninja has organized a new year party and wants to verify if the guests are programmers by challenging them with a coding task. As an invited programmer, you're tasked to so...read more
Compute the number of valid permutations of integers from 0 to N-1 such that at least K positions satisfy ARR[I] = I.
Use dynamic programming to solve the problem efficiently.
Consider the cases where K is equal to N or N-1 separately.
Modulo the result by 10^9 + 7 to avoid overflow issues.
Q3. Fibonacci Membership Check
Given an integer N
, determine if it is a member of the Fibonacci series. Return true
if the number is a member of the Fibonacci series, otherwise return false
.
Fibonacci Series Defini...read more
Check if a given integer is a member of the Fibonacci series.
Implement a function to check if the given number is a perfect square.
Check if 5*N^2 + 4 or 5*N^2 - 4 is a perfect square to determine Fibonacci membership.
Return true if the number is a perfect square of 5*N^2 + 4 or 5*N^2 - 4, otherwise false.
Q4. Maximum Meetings Problem Statement
Given the schedule of N meetings with their start time Start[i]
and end time End[i]
, you need to determine which meetings can be organized in a single meeting room such that t...read more
Given N meetings with start and end times, find the maximum number of meetings that can be organized in a single room without overlap.
Sort the meetings based on their end times.
Iterate through the sorted meetings and select the next meeting that does not overlap with the current meeting.
Keep track of the selected meetings and return their indices in the order they are organized.
Q5. Count Pairs with Difference K
Given an array of integers and an integer K
, determine and print the count of all pairs in the array that have an absolute difference of K
.
Input:
The first line of the input conta...read more
Count pairs in an array with a specific absolute difference.
Iterate through the array and for each element, check if the element + K or element - K exists in the array.
Use a hash set to store elements for constant time lookups.
Keep track of the count of valid pairs found.
Q6. K Subsets with Equal Sum Problem Statement
Determine whether it is possible to partition an array ARR
into K
subsets, each having an equal sum.
Example:
Input:
ARR = [3, 5, 2, 4, 4], K = 2
Output:
true
Explanat...read more
Yes, it is possible to partition an array into K subsets with equal sum.
Check if the total sum of the array is divisible by K.
Use backtracking to try all possible combinations of subsets.
Keep track of visited elements to avoid repetition.
Example: ARR = [3, 5, 2, 4, 4], K = 2. Possible subsets: [4, 5] and [2, 3, 4].
Q7. Valid Parentheses Problem Statement
Given a string 'STR' consisting solely of the characters “{”, “}”, “(”, “)”, “[” and “]”, determine if the parentheses are balanced.
Input:
The first line contains an integer...read more
The task is to determine if given strings containing only parentheses are balanced or not.
Iterate through each character in the string and use a stack to keep track of opening parentheses.
If a closing parenthesis is encountered, check if the stack is empty or if the top of the stack matches the corresponding opening parenthesis.
If all parentheses are balanced, the stack should be empty at the end.
Return 'Balanced' if the stack is empty, otherwise return 'Not Balanced'.
Q8. Missing Number Statement
Given an array ARR
of integers with size N
, where all elements appear an even number of times except for one element which appears an odd number of times, identify the element that appe...read more
Identify the element that appears an odd number of times in an array of integers where all other elements appear an even number of times.
Iterate through the array and use XOR operation to find the element that appears an odd number of times.
XOR of a number with itself is 0, so XOR of all elements will give the odd occurring element.
Return the result after XORing all elements in the array.
Q9. Rotational Equivalence of Strings Problem Statement
Given two strings 'P' and 'Q' of equal length, determine if string 'P' can be transformed into string 'Q' by cyclically rotating it to the right any number of...read more
Check if one string can be transformed into another by cyclically rotating it to the right.
Iterate through all possible rotations of string P and check if any of them match string Q.
Use string concatenation and substring operations to simulate the rotation.
Optimize the solution to O(N) time complexity by checking if string Q is a substring of P concatenated with itself.
Q10. Minimum Number of Platforms Needed Problem Statement
You are given the arrival and departure times of N trains at a railway station for a particular day. Your task is to determine the minimum number of platform...read more
The problem involves determining the minimum number of platforms needed at a railway station based on arrival and departure times of trains.
Sort the arrival and departure times in ascending order.
Use two pointers to keep track of overlapping schedules.
Increment platform count when a train arrives and decrement when it departs.
Return the maximum platform count needed.
Q11. Pair Sum Problem Statement
You are given an integer array 'ARR' of size 'N' and an integer 'S'. Your task is to find and return a list of all pairs of elements where each sum of a pair equals 'S'.
Note:
Each pa...read more
Find pairs of elements in an array that sum up to a given value, sorted in a specific order.
Iterate through the array and use a hashmap to store the difference between the target sum and each element.
Check if the current element's complement exists in the hashmap, if so, add the pair to the result list.
Sort the pairs based on the criteria mentioned in the question.
Return the list of pairs as the final output.
Q12. Sort a "K" Sorted Doubly Linked List Problem Statement
You are given a doubly linked list with 'N' nodes, where each node can deviate at most 'K' positions from its actual position in the sorted list. Your task...read more
Sort a doubly linked list with nodes that can deviate at most K positions from their actual position in the sorted list.
Iterate through the doubly linked list and maintain a window of size K+1 to sort the elements within the window.
Use insertion sort within the window to sort the elements efficiently.
Repeat the process until the entire list is sorted.
Time complexity can be optimized to O(N*log(K)) using a priority queue.
Q13. Code Optimization Problem
Ninja encountered an issue with a practice problem where certain test cases could not be passed due to high time complexity. You are provided with a snippet of pseudocode, and your tas...read more
Optimize pseudocode to compute XOR operations in a given range and return sum modulo 1000000007.
Use bitwise XOR properties to optimize the computation.
Avoid unnecessary nested loops by simplifying the logic.
Consider using modular arithmetic to handle large numbers efficiently.
Q14. Stock Trading Maximum Profit Problem
Given the stock prices for 'N' days, your goal is to determine the maximum profit that can be achieved. You can buy and sell the stocks any number of times but can only hold...read more
The goal is to determine the maximum profit that can be achieved by buying and selling stocks on different days.
Iterate through the stock prices and buy on days when the price is lower than the next day, and sell on days when the price is higher than the next day.
Calculate the profit by summing up the differences between buying and selling prices.
Repeat the process for each test case and output the maximum profit possible for each case.
Q15. First Non-Repeating Character Problem Statement
You are given a string consisting of English alphabet characters. Your task is to identify and return the first character in the string that does not repeat. If e...read more
Identify and return the first non-repeating character in a string, or the first character if all characters repeat.
Iterate through the string to count the frequency of each character
Return the first character with a frequency of 1, or the first character if all characters repeat
Use a hashmap to store character frequencies efficiently
Q16. Count Ways To Reach The N-th Stair Problem Statement
You are given a number of stairs, N
. Starting at the 0th stair, you need to reach the Nth stair. Each time you can either climb one step or two steps. You ha...read more
The problem involves finding the number of distinct ways to climb to the Nth stair by taking one or two steps at a time.
Use dynamic programming to solve this problem efficiently.
The number of ways to reach the Nth stair is the sum of the number of ways to reach the (N-1)th stair and the (N-2)th stair.
Handle large inputs by taking modulo 10^9+7 to avoid overflow.
Example: For N=3, there are 3 ways to climb to the third stair: (0, 1, 2, 3), (0, 2, 3), and (0, 1, 3).
Q17. N-th Term Of Geometric Progression
Find the N-th term of a Geometric Progression (GP) series given the first term A, the common ratio R, and the term position N.
Explanation:
The general form of a GP series is ...read more
Calculate the N-th term of a Geometric Progression series given the first term, common ratio, and term position.
Iterate through each test case and apply the formula A * R^(N-1) to find the N-th term
Use modular arithmetic to handle large calculated terms by returning the result modulo 10^9 + 7
Q18. Trailing Zeros in Factorial Problem
Find the number of trailing zeroes in the factorial of a given number N
.
Input:
The first line contains an integer T
representing the number of test cases.
Each of the followi...read more
Count the number of trailing zeros in the factorial of a given number.
To find the number of trailing zeros in N!, count the number of factors of 5 in the prime factorization of N.
Each factor of 5 contributes to a trailing zero in the factorial.
For example, for N=10, there are 2 factors of 5 in the prime factorization (5 and 10), so there are 2 trailing zeros.
Q19. Remove String from Linked List Problem
You are provided with a singly linked list where each node contains a single character, along with a string 'STR'. Your task is to remove all occurrences of the string 'ST...read more
Remove all occurrences of a given string from a singly linked list by starting from the end of the list.
Traverse the linked list from the end to the beginning to efficiently remove the string occurrences.
Check for the string 'STR' in each node and remove it if found.
Continue checking for new occurrences of 'STR' after removal to ensure all instances are removed.
Return the head of the modified linked list after processing each test case.
Q20. Clone a FULL linked list given a pointer and a random pointer
Clone a linked list with a random pointer.
Create a new node for each node in the original list.
Use a hash table to map the original nodes to their clones.
Iterate through the original list again and update the random pointers of the clone nodes.
Q21. What is a binary tree and implementation? what is the heap? Array and sorting? Coding Problem.
Binary tree is a data structure where each node has at most two children. Heap is a specialized tree-based data structure. Array is a collection of elements stored in contiguous memory locations.
Binary tree can be implemented using linked lists or arrays.
Heap is used to efficiently implement priority queues.
Sorting algorithms like bubble sort, insertion sort, merge sort, quick sort can be used to sort arrays.
Coding problem can be related to traversing a binary tree, implement...read more
Q22. Reverse a linked list (iterative AND Recursive)
Reverse a linked list using iterative and recursive methods.
Iterative method involves traversing the list and changing the pointers to reverse the order.
Recursive method involves calling the function recursively on the next node and changing the pointers.
Both methods have O(n) time complexity and O(1) space complexity.
Example: 1->2->3->4->5 becomes 5->4->3->2->1.
Q23. Introduction Mind checking Ready to relocate?
Yes, I am open to relocation for the right opportunity.
I am willing to relocate for a position that aligns with my career goals and offers growth opportunities.
I am open to considering relocation packages and assistance.
I am excited about the prospect of exploring new cities and cultures.
Examples: I have previously relocated for a job and found it to be a positive experience.
I am willing to discuss relocation during the interview process.
Q24. Partition to K Equal Sum Subsets Problem
Given an array of integers and a positive integer 'K', determine if it is possible to divide the array into 'K' non-empty subsets such that the sum of elements in each s...read more
The problem involves dividing an array into K subsets with equal sum.
Use backtracking to try all possible combinations of subsets.
Keep track of the sum of elements in each subset and check if they are equal to the target sum.
Optimize by sorting the array in descending order and assigning elements to subsets greedily.
Handle edge cases like when the sum of elements is not divisible by K.
Q25. Sort a "K" Sorted Doubly Linked List
Given a doubly-linked list with N
nodes, where each node’s position deviates at most K
positions from its position in the sorted list, your task is to sort this given doubly...read more
Sort a doubly linked list where each node's position deviates at most K positions from its position in the sorted list.
Iterate through the doubly linked list and maintain a min-heap of size K+1 to keep track of the next smallest element.
Remove the smallest element from the heap and add it to the sorted list. Update the heap with the next element from the removed node's next position.
Continue this process until all nodes are added to the sorted list.
Q26. Maximum Meetings Selection
You are tasked with scheduling meetings in a single meeting room. Given N
meetings, each with a start time Start[i]
and end time End[i]
, determine the maximum number of meetings that ...read more
Given start and end times of meetings, find the maximum number of meetings that can be scheduled in a single room.
Sort the meetings based on their end times in ascending order.
Iterate through the sorted meetings and select the ones that do not overlap with the previously selected meetings.
Keep track of the selected meetings and return their indices.
Q27. Nth Prime Number Problem Statement
Find the Nth prime number given a number N.
Explanation:
A prime number is greater than 1 and is not the product of two smaller natural numbers. A prime number has exactly two...read more
Find the Nth prime number given a number N.
A prime number is greater than 1 and is not the product of two smaller natural numbers
A prime number has exactly two distinct positive divisors: 1 and itself
Implement a function to find the Nth prime number based on the given input
Q28. Counting Derangements Problem
A derangement is a permutation of 'N' elements, where no element appears in its original position. For instance, a derangement of {0, 1, 2, 3} is {2, 3, 1, 0} because each element ...read more
Count the total number of derangements possible for a set of 'N' elements.
A derangement is a permutation where no element appears in its original position.
Use the formula for derangements: !n = n! * (1 - 1/1! + 1/2! - 1/3! + ... + (-1)^n/n!)
Return the answer modulo (10^9 + 7) to handle large results.
Q29. Count Palindrome Words in a String
Given a string 'S' consisting of words, your task is to determine the number of palindrome words within 'S'. A word is considered a palindrome if it reads the same backward as...read more
Count the number of palindrome words in a given string.
Split the string into words using whitespace as delimiter.
Check each word if it is a palindrome by comparing it with its reverse.
Increment a counter for each palindrome word found.
Output the total count of palindrome words for each test case.
Q30. Check If Binary Representation of a Number is Palindrome
Given an integer N
, determine if its binary representation is a palindrome.
Input:
The first line contains a single integer ‘T’ representing the number o...read more
Check if the binary representation of a number is a palindrome.
Convert the integer to binary representation.
Check if the binary representation is a palindrome by comparing it with its reverse.
Return true if it is a palindrome, false otherwise.
Q31. Merge k Sorted Linked Lists
You are provided with 'K' sorted linked lists, each sorted in increasing order. Your task is to merge all these lists into one single sorted linked list and return the head of the re...read more
Merge k sorted linked lists into one single sorted linked list.
Create a min-heap to store the heads of all linked lists.
Pop the smallest element from the heap and add it to the result list.
If the popped element has a next element, push it back to the heap.
Repeat until all elements are merged into a single sorted list.
Q32. Duplicate Subtrees Problem Statement
Given a binary tree, return the root values of all duplicate subtrees. Two subtrees are considered duplicate if they have the same structure with identical node values. For ...read more
Find root values of duplicate subtrees in a binary tree.
Traverse the tree in a bottom-up manner to identify duplicate subtrees.
Use a hashmap to store the subtree structures and their frequencies.
Return the root values of duplicate subtrees based on hashmap entries.
Q33. Quick and merge time complexity and when worst case happens in quick sort
Quick sort has O(n log n) time complexity on average, O(n^2) worst case. Merge sort has O(n log n) time complexity always.
Quick sort has an average time complexity of O(n log n) due to its divide-and-conquer approach.
Worst case for quick sort occurs when the pivot element is either the smallest or largest element in the array, leading to O(n^2) time complexity.
Merge sort always has a time complexity of O(n log n) due to its consistent splitting and merging of subarrays.
Q34. Sort 0 and 1 Problem Statement
Given an integer array ARR
of size N
containing only integers 0 and 1, implement a function to sort this array. The solution should scan the array only once without using any addi...read more
Sort an array of 0s and 1s in linear time without using additional arrays.
Use two pointers approach to swap 0s to the left and 1s to the right.
Maintain two pointers, one for 0s and one for 1s, and iterate through the array.
Swap elements at the two pointers based on the values encountered.
Continue until the two pointers meet in the middle of the array.
Q35. String Rotation Problem Statement
You are given a string named str
and an integer D
. Your task is to perform both left (anticlockwise) and right (clockwise) rotations on the given string by D
units, starting fr...read more
Implement left and right string rotations by D units on a given string.
Implement leftRotate() function to return string after left rotation by D units.
Implement rightRotate() function to return string after right rotation by D units.
Consider handling edge cases like empty string or D exceeding string length.
Example: For input 'coding', D=2, leftRotate() should return 'dingco' and rightRotate() should return 'ngcodi'.
Q36. Word Break Problem Statement
You are given a list of N
strings called A
. Your task is to determine whether you can form a given target string by combining one or more strings from A
.
The strings from A
can be u...read more
Given a list of strings, determine if a target string can be formed by combining one or more strings from the list.
Iterate through all possible combinations of strings from the list to check if they can form the target string.
Use recursion to try different combinations of strings.
Keep track of the current position in the target string and the strings used so far.
Return true if the target string can be formed, false otherwise.
Q37. Character Formation Check
Determine if the second string STR2
can be constructed using characters from the first string STR1
. Both strings may include any characters.
Input:
The first line contains an integer T...read more
Check if second string can be formed using characters from the first string.
Iterate through each character in STR2 and check if it exists in STR1.
Use a hashmap to store the frequency of characters in STR1 for efficient lookup.
Return 'YES' if all characters in STR2 are found in STR1, otherwise return 'NO'.
Q38. Detect and Remove Loop in Linked List
For a given singly linked list, identify if a loop exists and remove it, adjusting the linked list in place. Return the modified linked list.
Expected Complexity:
Aim for a...read more
Detect and remove loop in a singly linked list in place with O(n) time complexity and O(1) space complexity.
Use Floyd's Cycle Detection Algorithm to identify the loop in the linked list.
Once the loop is detected, use two pointers to find the start of the loop.
Adjust the pointers to remove the loop and return the modified linked list.
Q39. Trapping Rainwater Problem Statement
You are given an array ARR
of long type, which represents an elevation map where ARR[i]
denotes the elevation of the ith
bar. Calculate the total amount of rainwater that ca...read more
Calculate the total amount of rainwater that can be trapped within given elevation map.
Iterate through the array to find the maximum height on the left and right of each bar.
Calculate the amount of water that can be trapped above each bar by taking the minimum of the maximum heights on the left and right.
Sum up the trapped water above each bar to get the total trapped water for the elevation map.
Q40. Spiral Order Traversal of a Binary Tree
Given a binary tree with N
nodes, your task is to output the Spiral Order traversal of the binary tree.
Input:
The input consists of a single line containing elements of ...read more
The task is to output the Spiral Order traversal of a binary tree given in level order.
Implement a function that returns the spiral order traversal as a list
Traverse the binary tree in a spiral order alternating between left to right and right to left
Use a queue to keep track of nodes at each level
Handle null nodes represented by -1 in the input
Q41. Jumping Game Problem Statement
In this problem, you have ‘n’ carrots lined up and denoted by numbers 1 through ‘n’. There are ‘k’ rabbits, and each rabbit can jump to carrots that are multiples of its unique ju...read more
Calculate uneaten carrots after rabbits jump based on their unique factors.
Iterate through each rabbit's jumping factor and mark the carrots they land on as eaten
Calculate the remaining uneaten carrots by counting the ones not marked as eaten
Consider using a data structure like an array to keep track of eaten carrots efficiently
Q42. Distribute N Candies Among K People
Explanation: Sanyam wishes to distribute 'N' candies among 'K' friends. The friends are arranged based on Sanyam's order of likeness. He initially distributes candies such th...read more
Distribute N candies among K people in Sanyam's order of likeness, incrementing distribution by K each round until all candies are distributed.
Distribute candies starting from 1st friend, incrementing by K each round
If remaining candies are fewer than what a friend is supposed to receive, stop distribution
Output the number of candies each friend ends up with at the end of distribution
Q43. Reverse Linked List Problem Statement
Given a Singly Linked List of integers, your task is to reverse the Linked List by altering the links between the nodes.
Input:
The first line of input is an integer T, rep...read more
Reverse a singly linked list by altering the links between nodes.
Iterate through the linked list and reverse the links between nodes
Use three pointers to keep track of the current, previous, and next nodes
Update the links between nodes to reverse the list
Return the head of the reversed linked list
Q44. Height of Binary Tree
You are provided with the Inorder and Level Order traversals of a Binary Tree composed of integers. Your goal is to determine the height of this Binary Tree without actually constructing i...read more
Calculate the height of a Binary Tree given its Inorder and Level Order traversals without constructing it.
Use the properties of Inorder and Level Order traversals to determine the height of the Binary Tree.
The height of a Binary Tree is the number of edges on the longest path from the root to a leaf node.
Consider edge cases like a single node tree or empty tree when calculating the height.
Q45. Count Pairs with Given Sum
Given an integer array/list arr
and an integer 'Sum', determine the total number of unique pairs in the array whose elements sum up to the given 'Sum'.
Input:
The first line contains ...read more
Count the total number of unique pairs in an array whose elements sum up to a given value.
Use a hashmap to store the frequency of each element in the array.
Iterate through the array and for each element, check if (Sum - current element) exists in the hashmap.
Increment the count of pairs if the complement exists in the hashmap.
Divide the count by 2 to avoid counting duplicates (arr[i], arr[j]) and (arr[j], arr[i]) separately.
Q46. Reverse Stack with Recursion
Reverse a given stack of integers using recursion. You must accomplish this without utilizing extra space beyond the internal stack space used by recursion. Additionally, you must r...read more
Reverse a given stack of integers using recursion without extra space or loop constructs.
Use recursion to pop all elements from the original stack and store them in function call stack.
Once the stack is empty, push the elements back in reverse order using recursion.
Ensure to handle base cases for empty stack or single element stack.
Example: If the input stack is [1, 2, 3], after reversal it should be [3, 2, 1].
Q47. Remove a linked list node without head or tail pointer given
Removing a node from a linked list without head or tail pointer
Use the node to be removed's next node to copy its data and then delete the next node
Update the current node's next pointer to skip the next node
Q48. Prime Numbers Identification
Given a positive integer N
, your task is to identify all prime numbers less than or equal to N
.
Explanation:
A prime number is a natural number greater than 1 that has no positive d...read more
Identify all prime numbers less than or equal to a given positive integer N.
Iterate from 2 to N and check if each number is prime
Use the Sieve of Eratosthenes algorithm for efficient prime number identification
Optimize by only checking up to the square root of N for divisors
Q49. Median of Two Sorted Arrays
Given two sorted arrays A
and B
of sizes N
and M
, find the median of the merged array formed by combining arrays A
and B
. If the total number of elements, N + M
, is even, the median ...read more
Find the median of two sorted arrays by merging them and calculating the middle element(s).
Merge the two sorted arrays into one sorted array.
Calculate the median based on the total number of elements in the merged array.
If the total number of elements is even, take the mean of the two middle elements as the median.
Q50. Maximum Sum Path in a Binary Tree
Your task is to determine the maximum possible sum of a simple path between any two nodes (possibly the same) in a given binary tree of 'N' nodes with integer values.
Explanati...read more
Find the maximum sum of a simple path between any two nodes in a binary tree.
Use a recursive approach to traverse the binary tree and calculate the maximum sum path.
Keep track of the maximum sum path found so far while traversing the tree.
Consider negative values in the path sum calculation to handle cases where the path can start and end at different nodes.
Handle cases where the path can go through the root node or not.
Q51. DFS Traversal Problem Statement
Given an undirected and disconnected graph G(V, E)
, where V
is the number of vertices and E
is the number of edges, the connections between vertices are provided in the 'GRAPH' m...read more
DFS traversal to find connected components in an undirected and disconnected graph.
Use Depth First Search (DFS) algorithm to traverse the graph and find connected components.
Maintain a visited array to keep track of visited vertices.
For each unvisited vertex, perform DFS to explore all connected vertices and form a connected component.
Q52. Properties of MST in an Undirected Graph
You have a simple undirected graph G = (V, E)
where each edge has a distinct weight. Consider an edge e
as part of this graph. Determine which of the given statements re...read more
In an undirected graph with distinct edge weights, the lightest edge in a cycle is included in every MST, while the heaviest edge is excluded.
The lightest edge in a cycle is always included in every MST of the graph.
The heaviest edge in a cycle is always excluded from every MST of the graph.
This property holds true for all simple undirected graphs with distinct edge weights.
Q53. Your favorite programming language and why
My favorite programming language is Python because of its simplicity, readability, and versatility.
Python is known for its clean and readable syntax, making it easy to learn and understand.
Python has a large standard library and many third-party libraries, allowing for rapid development of a wide range of applications.
Python is versatile and can be used for web development, data analysis, machine learning, automation, and more.
Q54. 4. React: What is Virtual DOM, useState and different types of Hooks in React
Virtual DOM is a lightweight copy of the actual DOM, useState is a hook for managing state in functional components, and Hooks are functions that let you use state and other React features in functional components.
Virtual DOM is a lightweight copy of the actual DOM that React uses to improve performance by updating only the necessary parts of the actual DOM.
useState is a hook in React that allows functional components to have state. It returns an array with the current state ...read more
Q55. Find The Closest Perfect Square Problem Statement
You are given a positive integer N
. Your task is to find the perfect square number that is closest to N
and determine the number of steps required to reach that...read more
Find the closest perfect square to a given positive integer and determine the number of steps required to reach that number.
Iterate through perfect squares starting from 1 until the square is greater than the given number
Calculate the distance between the perfect square and the given number
Return the closest perfect square and the distance as output
Q56. 1.what is stack? 2.undo-redo 3.backward and forward in the browser 4.polymorphism 5.given array find the frequency of each element. 6.Pseudo code is given on screen asked for output ...topic :--multiple inherit...
read moreA technical interview question on various computer science concepts.
Stack is a data structure that follows the Last-In-First-Out (LIFO) principle.
Undo-Redo is a feature that allows users to reverse or repeat actions in software applications.
Backward and forward in the browser refers to navigating to previously visited or next pages.
Polymorphism is the ability of an object to take on multiple forms or behaviors.
To find the frequency of each element in an array, iterate through...read more
Q57. 5. SQL: Different Types of triggers, define index and its types
Triggers in SQL are special stored procedures that are automatically executed when certain events occur in a database. Indexes in SQL are used to speed up the retrieval of data from tables.
Types of triggers: DML triggers (insert, update, delete), DDL triggers (create, alter, drop), and Logon triggers.
Indexes in SQL are used to quickly retrieve data from tables. Types of indexes include clustered, non-clustered, unique, and composite indexes.
Example: CREATE TRIGGER trgAfterIns...read more
Q58. Suppose we have more 2 interfaces with the same default method. What will happen when we try to implment both the interfaces in the same class.?
The class will have to provide its own implementation of the conflicting default method.
When implementing multiple interfaces with the same default method, a class must provide its own implementation of the conflicting method.
The class cannot inherit the default implementation from both interfaces.
The class can choose to implement one of the default methods and provide its own implementation for the other.
Alternatively, the class can provide a completely new implementation fo...read more
Q59. Can Two Primary keys can be made possible in Sql Table ?
No, only one primary key can be defined in a SQL table.
Primary key ensures uniqueness of each record in a table.
A table can have only one primary key constraint.
However, a composite primary key can be created using multiple columns.
Keys in database management systems are unique identifiers for rows in a table.
Keys ensure data integrity by enforcing uniqueness and relationships between tables.
Primary key uniquely identifies each record in a table (e.g. employee ID).
Foreign key establishes a link between two tables by referencing the primary key of another table.
Q61. 1. Responsibility of Business analyst, product owner 2. Difference between Ready and Done 3. Questions related Change and impact analysis 4. Questions about Scrum events 5. Case study etc Duration : 30 mins
Interview questions for Senior Staff Consultant role
Business analyst responsible for gathering and analyzing business requirements
Product owner responsible for prioritizing and managing product backlog
Ready means the task is ready to be worked on, while Done means the task is completed
Change analysis involves identifying the impact of changes on project scope, timeline, and budget
Scrum events include Sprint planning, Daily Scrum, Sprint review, and Sprint retrospective
Case st...read more
Q62. 3. JavaScript: difference between var and let keyword, closure function
var keyword has function scope, let keyword has block scope. Closure function is a function defined inside another function.
var keyword has function scope, let keyword has block scope
Variables declared with var are hoisted to the top of their function, let variables are not hoisted
Closure function is a function defined inside another function, has access to the outer function's variables
Q63. Swap two no without third variable
To swap two numbers without using a third variable, use arithmetic operations.
Use addition and subtraction to swap the numbers. For example, a=5, b=10. a=a+b, b=a-b, a=a-b will swap the values.
Another method is to use XOR operation. For example, a=5, b=10. a=a^b, b=a^b, a=a^b will swap the values.
Q64. what is MVVM and design patterns
MVVM is a design pattern that separates the UI from the business logic, promoting code reusability and maintainability.
MVVM stands for Model-View-ViewModel
Model represents the data and business logic
View is the UI components that the user interacts with
ViewModel acts as a mediator between the Model and View, handling user inputs and updating the Model
Design patterns are reusable solutions to common problems in software design
Examples of design patterns include Singleton, Fact...read more
Q65. What are the different types of data binding in Angular?
Data binding in Angular allows automatic synchronization of data between the model and the view.
Interpolation: {{ }} - binds data from the component to the view
Property binding: [] - binds data from the component to an element property
Event binding: () - binds an event from the view to a method in the component
Two-way binding: [()] - combines property and event binding to achieve two-way data flow
Q66. When to use Inline Template vs External Template in Angular?
Inline templates are used for small, simple templates, while external templates are used for larger, complex templates.
Inline templates are defined within the component's TypeScript file using the template property.
External templates are defined in separate HTML files and linked to the component using the templateUrl property.
Inline templates are useful for small components or when the template is simple and doesn't require much HTML code.
External templates are beneficial for...read more
Q67. Remove nth element from array
Remove the nth element from an array of strings
Use the splice method to remove the element at the specified index
Remember that array indices start at 0
Example: array.splice(n, 1) will remove the element at index n
Q68. 1. Explain Middleware in .Net Core
Middleware in .Net Core is a software component that acts as a bridge between an application's request processing pipeline and the server.
Middleware components are executed in the order they are added to the pipeline.
They can perform tasks like authentication, logging, error handling, etc.
Middleware can be added using the 'UseMiddleware' method in the 'Configure' method of Startup class.
Q69. Tell Travelling Salesman Problem Optimal Solution Approach
The optimal solution approach for the Travelling Salesman Problem involves using algorithms such as the Nearest Neighbor Algorithm and the 2-Opt Algorithm.
The Nearest Neighbor Algorithm starts at a random city and selects the nearest unvisited city as the next stop.
The 2-Opt Algorithm involves swapping two edges in the tour to see if it results in a shorter distance.
Other algorithms include the Genetic Algorithm and the Simulated Annealing Algorithm.
The optimal solution is no...read more
Q70. What are the two types of compiler in angular?
The two types of compiler in Angular are JIT (Just-in-Time) compiler and AOT (Ahead-of-Time) compiler.
JIT compiler compiles the code at runtime in the browser.
AOT compiler compiles the code before the application is deployed to the browser.
JIT compilation is slower but allows for faster development and debugging.
AOT compilation is faster but requires additional build step before deployment.
Q71. Which module is used for http calls in Angular?
HttpClient module is used for http calls in Angular.
HttpClient module is part of the @angular/common/http package.
It provides a simplified API for making HTTP requests.
It supports various HTTP methods like GET, POST, PUT, DELETE, etc.
It also supports features like request/response headers, query parameters, error handling, etc.
Example: import { HttpClient } from '@angular/common/http';
Q72. Reverse The Linked list
Reverse a linked list by changing the direction of pointers
Start from the head of the linked list
Iterate through the list and change the direction of pointers to reverse the list
Update the head to point to the last node as the new head
Q73. how to prioritize stories if stakeholders say all are equally important
Prioritize based on impact, urgency, and dependencies
Assess impact of each story on overall project goals
Consider urgency and deadlines associated with each story
Evaluate dependencies between stories and prioritize those that unlock others
Collaborate with stakeholders to understand their reasoning and negotiate priorities
Use techniques like MoSCoW method or Value vs Effort matrix to prioritize effectively
Q74. What are projections in Spring Data JPA?
Projections in Spring Data JPA allow customizing the shape of the data returned from a query.
Projections are used to retrieve specific fields or a subset of fields from an entity.
They help in reducing the amount of data transferred over the network.
Projections can be defined using interfaces or classes.
They can be used with both JPQL and native SQL queries.
Projections can be used to fetch related entities as well.
Q75. Difference between Union And Union All in SQL?
Union combines and removes duplicates, Union All combines all rows including duplicates.
Union merges the results of two or more SELECT statements into a single result set.
Union All returns all rows from all SELECT statements, including duplicates.
Union requires the same number of columns in all SELECT statements, while Union All does not.
Union sorts the result set and removes duplicates, while Union All does not.
Union is slower than Union All because it performs additional pr...read more
Q76. explain Clean Architecture
Clean Architecture is a software design approach that separates concerns and enforces a clear structure for code organization.
Clear separation of concerns between different layers (e.g. presentation, domain, data)
Dependency Rule: inner layers should not depend on outer layers
Use of interfaces to define boundaries between layers
Focus on testability and maintainability
Examples: Hexagonal Architecture, Onion Architecture
Q77. explain solid principles
SOLID principles are a set of five design principles in object-oriented programming to make software designs more understandable, flexible, and maintainable.
Single Responsibility Principle (SRP) - A class should have only one reason to change.
Open/Closed Principle (OCP) - Software entities should be open for extension but closed for modification.
Liskov Substitution Principle (LSP) - Objects of a superclass should be replaceable with objects of its subclasses without affecting...read more
Q78. Difference Abstract Method vs Interface ?
Abstract methods are methods without implementation in abstract classes, while interfaces are contracts that define methods.
Abstract classes can have both abstract and non-abstract methods, while interfaces can only have abstract methods.
A class can implement multiple interfaces, but can only inherit from one abstract class.
Abstract classes can have constructors, while interfaces cannot.
Interfaces can have properties, while abstract classes can have fields.
Q79. Terminal vs Intermediate Operations in streams
Terminal operations in streams produce a result or a side effect, while intermediate operations transform or filter the data.
Terminal operations are the final operations in a stream pipeline, such as forEach, collect, or reduce.
Intermediate operations are operations that can be chained together, such as filter, map, or sorted.
Terminal operations trigger the processing of the stream and produce a result or a side effect.
Intermediate operations transform or filter the data in t...read more
Q80. How is the search in Hashmap O(1).
Hashmap search has constant time complexity O(1) due to its use of hash function and index-based storage.
Hashmap uses a hash function to generate a unique index for each key-value pair
This index is used to directly access the value in the underlying array
As long as the hash function is well-designed and the array is large enough, search time remains constant
Example: searching for a value with key 'John' in a hashmap of 1000 entries takes the same time as searching in a hashma...read more
Q81. Intents in android
Intents in Android are messaging objects used to request an action from another app component.
Intents are used to start activities, services, and broadcast receivers in Android.
There are two types of intents: explicit intents and implicit intents.
Explicit intents specify the component to start by name, while implicit intents specify the action to perform.
Example: Intent intent = new Intent(this, SecondActivity.class); startActivity(intent);
Q82. Find a pair with maximum product in array of integers
Find a pair of integers in an array with the maximum product.
Iterate through the array and keep track of the maximum and second maximum values.
Consider negative numbers and zero.
Time complexity: O(n)
Q83. What are Progressive Design Pattern?
Progressive design patterns are strategies used in web development to enhance user experience by gradually loading content and features.
Progressive enhancement: Start with a basic version of the website and progressively enhance it with more advanced features for users with modern browsers.
Lazy loading: Load only the necessary content initially and then load additional content as the user scrolls down the page.
Responsive design: Design websites to adapt to different screen si...read more
Q84. try vs try-with-resources
try vs try-with-resources
The 'try' statement is used to define a block of code to be tested for exceptions.
The 'try-with-resources' statement is used to automatically close resources that implement the AutoCloseable interface.
Try-with-resources is more concise and less error-prone compared to try-catch-finally.
Try-with-resources can handle multiple resources in a single statement.
Q85. Iterator vs ListIterator
Iterator is a universal interface for iterating over a collection, while ListIterator is a specialized interface for iterating over lists.
Iterator can only move forward, while ListIterator can move in both directions.
ListIterator has additional methods like previous(), hasPrevious(), and add().
ListIterator is only available for List implementations, while Iterator can be used with any collection.
Q86. Promises vs Observables
Promises are used for asynchronous programming in JavaScript, while Observables are used for reactive programming.
Promises represent a single value that may be available now or in the future.
Observables represent a stream of values that can be emitted over time.
Promises are eager, meaning they start executing as soon as they are created.
Observables are lazy, meaning they only start executing when subscribed to.
Promises can be chained using .then() to handle success or failure...read more
Q87. Constructor vs ngOnInit
Constructor is a special method used to initialize an object, while ngOnInit is a lifecycle hook in Angular.
Constructor is used to create and initialize an object of a class.
ngOnInit is a lifecycle hook in Angular that is called after the component is initialized.
Constructor is defined using the constructor keyword, while ngOnInit is a method defined in the component class.
Constructor is called only once during the creation of an object, while ngOnInit is called every time th...read more
Q88. What is binary search tree
A binary search tree is a data structure in which each node has at most two children, with the left child being less than the parent and the right child being greater.
Nodes are arranged in a hierarchical order where each node has a value and two child nodes.
Left child node has a value less than its parent node, while the right child node has a value greater than its parent node.
Binary search trees allow for efficient searching, insertion, and deletion operations.
Q89. Output of java program
Cannot answer without knowing the java program
Need to know the code to determine output
Output can vary based on input and logic
Can provide answer if given the program
More about working at Nagarro







Top HR Questions asked in Nagarro for Freshers
Interview Process at Nagarro for Freshers

Top Interview Questions from Similar Companies








Reviews
Interviews
Salaries
Users/Month

