Samsung
40+ ITC Interview Questions and Answers
Q1. Remove Consecutive Duplicates Problem Statement
For a given string str
, remove all the consecutive duplicate characters.
Example:
Input:
Input String: "aaaa"
Output:
Expected Output: "a"
Input:
Input String: "a...read more
Remove consecutive duplicate characters from a given string.
Iterate through the string and compare each character with the previous one.
If the current character is different from the previous one, add it to the result string.
Return the result string as the output.
Q2. Count Leaf Nodes in a Binary Tree
Count the number of leaf nodes present in a given binary tree. A binary tree is a data structure where each node has at most two children, known as the left child and the right...read more
Count the number of leaf nodes in a binary tree where each node has at most two children.
Traverse the binary tree and count nodes with both children as NULL.
Use recursion to check each node in the tree.
Leaf nodes have no child nodes.
Example: For input 20 10 35 5 15 30 42 -1 13 -1 -1 -1 -1 -1 -1 -1, output should be 4.
Q3. Game of Stones Problem Statement
Two players, 'Ale' and 'Bob', are playing a game with a pile of stones. Your task is to determine the winner if both play optimally.
Rules of the Game:
1. On each turn, a player...read more
Determine the winner of a game where two players take stones alternately, with specific rules.
Implement a recursive function to simulate the game, considering the rules provided.
Check if the current player can take any stones, if not, the other player wins.
Return 'Ale' if 'Ale' will win the game, otherwise return 'Bob'.
Q4. Maximum Sum Path from Leaf to Root
Given a binary tree with 'N' nodes, identify the path from a leaf node to the root node that has the maximum sum among all root-to-leaf paths.
Example:
All the possible root t...read more
Find the path from a leaf node to the root node with the maximum sum in a binary tree.
Traverse the binary tree from leaf to root while keeping track of the sum of each path.
Compare the sums of all paths and return the path with the maximum sum.
Use recursion to traverse the tree efficiently.
Consider negative values in the tree when calculating the sum of paths.
Q5. 0-1 Knapsack Problem Statement
You are tasked with determining the maximum profit a thief can earn. The thief is looting a store and can carry a maximum weight 'W' in his knapsack. There are 'N' items, each wit...read more
The 0-1 Knapsack Problem involves maximizing profit by selecting items with known weights and values within a given weight capacity.
Understand the problem: Given items with weights and values, determine the maximum profit the thief can achieve within the knapsack's weight capacity.
Dynamic Programming: Use dynamic programming to solve the problem efficiently by considering the weight constraints and maximizing the total value.
Example: For input (1, 4, 10, [6, 1, 5, 3], [3, 6, ...read more
Q6. Merge Two Sorted Linked Lists Problem Statement
You are provided with two sorted linked lists. Your task is to merge them into a single sorted linked list and return the head of the combined linked list.
Input:...read more
Merge two sorted linked lists into a single sorted linked list without using additional space.
Create a dummy node to start the merged list
Compare the nodes of the two lists and link them accordingly
Move the pointer to the next node in the merged list
Handle cases where one list is empty or both lists are empty
Time complexity: O(n), Space complexity: O(1)
Q7. Largest Number in Binary Tree
You are provided with a Binary Tree consisting of 'N' nodes, where each node holds an integer value. Your task is to determine the largest possible number that can be formed by con...read more
Find the largest number that can be formed by concatenating all node values in a Binary Tree.
Traverse the Binary Tree in a way that ensures the largest values are concatenated first.
Use a custom comparator function to sort the node values in descending order before concatenating.
Handle null nodes by skipping them during concatenation.
Convert integer node values to strings for concatenation.
Implement a recursive function to traverse the Binary Tree and concatenate node values.
Q8. Bridge in Graph Problem Statement
Given an undirected graph with V vertices and E edges, your task is to find all the bridges in this graph. A bridge is an edge that, when removed, increases the number of conne...read more
Find all the bridges in an undirected graph by identifying edges that, when removed, increase the number of connected components.
Use Tarjan's algorithm to find bridges in the graph.
A bridge is an edge that, when removed, increases the number of connected components.
Identify bridges by performing DFS traversal and keeping track of low and discovery times.
Return the count of bridges and the vertices defining each bridge in non-decreasing order.
Q9. Minimum Insertions to Make a Palindrome
Given a string STR
of length N
composed of lowercase English letters, your task is to determine the minimum number of characters that need to be added to make the string ...read more
Given a string, find the minimum number of characters needed to make it a palindrome.
Iterate through the string from both ends and count the number of characters that need to be added to make it a palindrome.
Use dynamic programming to optimize the solution by considering subproblems.
Handle edge cases such as an already palindrome string or an empty string.
Example: For input 'abb', the output should be 1 as adding 'a' makes it 'abba', a palindrome.
Q10. Cousins of a Given Node in a Binary Tree
Given a binary tree with 'N' nodes and a specific node in this tree, you need to determine and return a sorted list of the values of the node's cousins. The cousins shou...read more
Given a binary tree and a specific node, return a sorted list of the node's cousins.
Traverse the binary tree to find the parent of the given node and its depth.
Traverse the tree again to find nodes at the same depth but with different parents.
Return the sorted list of cousin node values or -1 if no cousins exist.
Q11. Delete a Node from a Linked List
You are provided with a linked list of integers. Your task is to implement a function that deletes a node located at a specified position 'POS'.
Input:
The first line contains a...read more
Implement a function to delete a node from a linked list at a specified position.
Traverse the linked list to find the node at the specified position.
Update the pointers of the previous and next nodes to skip the node to be deleted.
Handle cases where the position is at the beginning or end of the linked list.
Ensure to free the memory of the deleted node to avoid memory leaks.
Q12. Rotate Matrix by 90 Degrees Problem Statement
Given a square matrix 'MATRIX' of non-negative integers, rotate the matrix by 90 degrees in an anti-clockwise direction using only constant extra space.
Input:
The ...read more
Rotate a square matrix by 90 degrees in an anti-clockwise direction using constant extra space.
Iterate through each layer of the matrix from outer to inner layers
Swap elements in groups of 4 to rotate the matrix
Handle odd-sized matrices separately by adjusting the center element if needed
Q13. Longest Increasing Subsequence Problem Statement
Given an array of integers with 'N' elements, determine the length of the longest subsequence where each element is greater than the previous element. This subse...read more
Find the length of the longest strictly increasing subsequence in an array of integers.
Use dynamic programming to keep track of the longest increasing subsequence ending at each element.
Initialize an array to store the length of the longest increasing subsequence ending at each index.
Iterate through the array and update the length of the longest increasing subsequence for each element.
Return the maximum value in the array as the length of the longest increasing subsequence.
Q14. Sum of Squares of First N Natural Numbers Problem Statement
You are tasked with finding the sum of squares of the first N
natural numbers for given test cases.
Input:
The first line contains an integer 'T', the...read more
Calculate the sum of squares of the first N natural numbers for given test cases.
Iterate through each test case and calculate the sum of squares using the formula: N*(N+1)*(2N+1)/6
Output the result for each test case on a new line
Handle constraints efficiently to avoid timeouts
Q15. Maximum Number from Linked List Problem Statement
Given a linked list where each node contains a single digit, your task is to construct the largest possible number using these digits.
Objective:
Print the maxi...read more
Given a linked list of single digits, construct the largest number possible.
Traverse the linked list to extract the digits
Sort the digits in descending order
Concatenate the sorted digits to form the maximum number
Q16. Maximum Subsequence Sum Without Three Consecutive Elements
Given an array A
of length N
consisting of positive integers, your task is to determine the maximum subsequence sum where no three consecutive elements...read more
Find the maximum subsequence sum from an array without selecting three consecutive elements.
Use dynamic programming to keep track of the maximum sum without selecting three consecutive elements.
At each index, consider the maximum sum with the current element included or excluded.
Handle edge cases where the array length is less than 3 separately.
Example: For input [1, 2, 3, 4], the maximum sum is 9 (1 + 3 + 4).
Q17. Word Search Problem Statement
Given a two-dimensional grid with 'N' rows and 'M' columns consisting of uppercase characters, and a string 'WORD', your task is to determine the number of times the word appears i...read more
Count the number of occurrences of a given word in a two-dimensional grid of characters.
Iterate through each cell in the grid and check if the word can be formed starting from that cell in any of the eight directions.
Use backtracking to explore all possible paths while matching the characters of the word.
Keep track of visited cells to avoid revisiting the same cell in the same path.
Return the count of occurrences of the word in the grid.
Q18. Move All Negative Numbers To Beginning
Rearrange a given array 'ARR' with 'N' integers so that all negative numbers appear before all positive numbers.
Follow Up:
Can you solve this in O(1) auxiliary space?
No...read more
Rearrange array with negative numbers at the beginning, order not important.
Iterate through the array and swap negative numbers to the beginning using two pointers approach.
Maintain one pointer for negative numbers and another for positive numbers.
Time complexity: O(N), Space complexity: O(1).
Q19. Shortest Path in a Binary Maze Problem Statement
Given a maze represented as a binary rectangular matrix of size M*N, where each element can either be 0 or 1, determine the length of the shortest path from a gi...read more
Find the length of the shortest path in a binary maze from a given source to destination.
Use Breadth First Search (BFS) algorithm to find the shortest path in the binary maze.
Create a queue to store the cells to be visited and keep track of visited cells to avoid revisiting them.
Check for valid moves in all four directions and update the distance to reach each cell.
Return the length of the shortest path if it exists, else return -1.
Example: For the given input, the shortest p...read more
Q20. Reverse Linked List Problem Statement
Given a singly linked list of integers, return the head of the reversed linked list.
Example:
Initial linked list: 1 -> 2 -> 3 -> 4 -> NULL
Reversed linked list: 4 -> 3 -> 2...read more
Reverse a singly linked list of integers and return the head of the reversed linked list.
Iterate through the linked list and reverse the pointers to point to the previous node instead of the next node.
Use three pointers to keep track of the current, previous, and next nodes while reversing the linked list.
Update the head of the reversed linked list as the last node encountered during the reversal process.
Q21. Reverse the String Problem Statement
You are given a string STR
which contains alphabets, numbers, and special characters. Your task is to reverse the string.
Example:
Input:
STR = "abcde"
Output:
"edcba"
Input...read more
Reverse a given string containing alphabets, numbers, and special characters.
Iterate through the string from the end to the beginning and append each character to a new string.
Use built-in functions like reverse() or slicing to reverse the string.
Handle special characters and numbers while reversing the string.
Ensure to consider the constraints on the input size and number of test cases.
Q22. Ceil Value from BST Problem Statement
Given a Binary Search Tree (BST) and an integer, write a function to return the ceil value of a particular key in the BST.
The ceil of an integer is defined as the smallest...read more
The problem involves finding the ceil value of a key in a Binary Search Tree (BST).
Traverse the BST to find the closest integer greater than or equal to the given key.
Compare the key with the current node value and update the ceil value accordingly.
Handle cases where the key is equal to a node value or falls between two nodes.
Implement a recursive or iterative solution to efficiently find the ceil value.
Q23. Sum of Digits Problem Statement
Given an integer 'N', continue summing its digits until the result is a single-digit number. Your task is to determine the final value of 'N' after applying this operation iterat...read more
Given an integer 'N', find the final single-digit value by summing its digits iteratively.
Iteratively sum the digits of the given integer until the result is a single-digit number
Output the final single-digit integer for each test case
Handle multiple test cases efficiently
Q24. Binary Tree to Doubly Linked List
Transform a given Binary Tree into a Doubly Linked List.
Ensure that the nodes in the Doubly Linked List follow the Inorder Traversal of the Binary Tree.
Input:
The first line ...read more
Convert a Binary Tree into a Doubly Linked List following Inorder Traversal.
Perform Inorder Traversal of the Binary Tree to get the nodes in order.
Create a Doubly Linked List by linking the nodes in the order obtained from Inorder Traversal.
Return the head of the Doubly Linked List as the output.
Q25. Convert Binary Tree to Mirror Tree
Convert a given binary tree into its mirror tree, where the left and right children of all non-leaf nodes are interchanged.
Input:
An integer ‘T’ denoting the number of test c...read more
Convert a binary tree into its mirror tree by interchanging left and right children of non-leaf nodes.
Traverse the tree in postorder fashion and swap the left and right children of each node.
Recursively call the function on the left and right subtrees.
Modify the tree in place without creating a new tree.
Q26. Find Shortest Path in a Tree
Given a tree with 'N' nodes and 'N - 1' distinct edges, along with two nodes 'N1' and 'N2', find and print the shortest path between 'N1' and 'N2'.
Explanation:
A tree is a nonlinea...read more
Find the shortest path between two nodes in a tree.
Use Breadth First Search (BFS) algorithm to find the shortest path in a tree.
Start BFS from one of the nodes and keep track of the parent of each node to reconstruct the path.
Once both nodes are reached, backtrack from both nodes to the root to find the common ancestor and then reconstruct the path.
Consider implementing a function to find the LCA (Lowest Common Ancestor) of two nodes in a tree.
Handle cases where one node is a...read more
Q27. Power of Two Problem Statement
Determine whether a given integer N
is a power of two. Return true
if it is, otherwise return false
.
Explanation
An integer 'N' is considered a power of two if it can be expressed...read more
Check if a given integer is a power of two or not.
Check if the given integer is positive.
Use bitwise operations to determine if it is a power of two.
Return true if it is a power of two, false otherwise.
Q28. Minimum Insertions to Make a String Palindrome
Determine the minimal number of characters needed to insert into a given string STR
to transform it into a palindrome.
Example:
Input:
STR = "abcaa"
Output:
2
Expl...read more
The task is to find the minimum number of characters needed to insert into a given string to make it a palindrome.
Use dynamic programming to find the longest palindromic subsequence of the given string.
Subtract the length of the longest palindromic subsequence from the length of the original string to get the minimum insertions required.
Handle edge cases like an empty string or a string that is already a palindrome.
Example: For input 'abcaa', the longest palindromic subsequen...read more
Q29. Merge Sort Linked List Problem Statement
You are given a singly linked list of integers. Your task is to sort the linked list using the merge sort algorithm.
Explanation:
Merge Sort is a divide and conquer algo...read more
Implement merge sort algorithm to sort a singly linked list of integers.
Divide the linked list into two halves using slow and fast pointer technique.
Recursively sort the two halves.
Merge the sorted halves using a merge function.
Handle base cases like empty list or single node list.
Ensure the termination of the linked list with -1 at the end.
Q30. Longest Palindromic Substring Problem Statement
You are provided with a string STR
of length N
. The goal is to identify the longest palindromic substring within this string. In cases where multiple palindromic ...read more
Given a string, find the longest palindromic substring, prioritizing the one with the smallest start index.
Iterate through the string and expand around each character to find palindromes
Keep track of the longest palindrome found, updating it as needed
Return the longest palindromic substring with the smallest start index
Q31. Triplets with Given Sum Problem
Given an array or list ARR
consisting of N
integers, your task is to identify all distinct triplets within the array that sum up to a specified number K
.
Explanation:
A triplet i...read more
Identify all distinct triplets within an array that sum up to a specified number.
Iterate through all possible triplets using three nested loops.
Check if the sum of the triplet equals the target sum.
Print the triplet if found, else print -1.
Q32. Implementing a Priority Queue Using Heap
Ninja has been tasked with implementing a priority queue using a heap data structure. However, he is currently busy preparing for a tournament and has requested your ass...read more
Implement a priority queue using a heap data structure with push, pop, getMaxElement, and isEmpty functions.
Implement push function to insert element into the queue
Implement pop function to remove the largest element from the queue
Implement getMaxElement function to return the largest element
Implement isEmpty function to check if the queue is empty
Q33. AVL Tree Insertion Task
Create an AVL tree from scratch. You will be provided with ‘N’ values representing node values you need to insert into the AVL tree. After inserting all values, return the root of the AV...read more
Implement a function to create an AVL tree from scratch by inserting given values and return the root of the tree.
Create a Node class with data, left, and right pointers for the AVL tree nodes.
Implement rotation functions (left rotation, right rotation) to maintain AVL tree balance.
Update the height and balance factor of nodes after each insertion to ensure AVL tree properties are maintained.
Q34. Palindrome Linked List Problem Statement
You are provided with a singly linked list of integers. Your task is to determine whether the given singly linked list is a palindrome. Return true
if it is a palindrome...read more
Check if a given singly linked list is a palindrome or not.
Use two pointers approach to find the middle of the linked list
Reverse the second half of the linked list
Compare the first half with the reversed second half to determine if it's a palindrome
Q35. BST to Greater Tree Conversion
Convert a given binary search tree (BST) with 'N' nodes into a Greater Tree. In this transformation, each node's data is modified to the sum of the original node's data plus the s...read more
Convert a given BST into a Greater Tree by updating each node's data to the sum of original data and all greater nodes' data.
Traverse the BST in reverse inorder (right, root, left) to update each node's data with the sum of all greater nodes' data.
Keep track of the running sum of nodes visited so far to update the current node's data.
Modify the BST in place without using any extra data structures.
Example: Input BST: 4 1 6 0 2 5 7 -1 -1 -1 3 -1 -1 -1 -1. Output Greater Tree: 2...read more
Q36. Remove BST Keys Outside Given Range
Given a Binary Search Tree (BST) and a specified range [min, max], your task is to remove all keys from the BST that fall outside this range. The BST should remain valid afte...read more
Remove BST keys outside given range while maintaining validity of BST.
Traverse the BST in inorder fashion and remove nodes outside the specified range.
Recursively call the function on left and right subtrees.
Adjust the pointers of parent nodes accordingly after removing nodes.
Ensure the BST remains valid after modifications.
Return the inorder traversal of the adjusted BST.
Q37. Water Supply Optimization Problem
Given N houses in a village, determine the minimum cost to supply water to all houses either by building wells in the houses or by connecting them with pipes.
Explanation:
For ...read more
Determine the minimum cost to supply water to all houses in a village by building wells or connecting them with pipes.
Iterate through all possible connections and choose the minimum cost between building a well or connecting two houses with a pipe.
Use a minimum spanning tree algorithm like Kruskal's or Prim's to find the optimal cost.
Consider the cost of building wells and connecting pipes to minimize the total cost.
Example: For the input (3 2, 1 2 2, 1 2 1, 2 3 1), the optim...read more
Q38. Minimum Jumps Problem Statement
Bob and his wife are in the famous 'Arcade' mall in the city of Berland. This mall has a unique way of moving between shops using trampolines. Each shop is laid out in a straight...read more
Find the minimum number of trampoline jumps Bob needs to make to reach the final shop, or return -1 if it's impossible.
Use Breadth First Search (BFS) to find the minimum number of jumps needed.
Keep track of the visited shops to avoid revisiting them.
If a shop has an Arr value of 0, it is impossible to reach the last shop.
Return -1 if the last shop cannot be reached.
Q39. Stack using Two Queues Problem Statement
Develop a Stack Data Structure to store integer values using two Queues internally.
Your stack implementation should provide these public functions:
Explanation:
1. Cons...read more
Implement a stack using two queues to store integer values with specified functions.
Use two queues to simulate stack operations efficiently.
Maintain one queue for storing elements and another for temporary storage during push operation.
Ensure to handle edge cases like empty stack and maximum size limit.
Example: Push operation involves transferring elements from one queue to another before adding the new element.
Q40. Merge Sort Problem Statement
You are given a sequence of numbers, ARR
. Your task is to return a sorted sequence of ARR
in non-descending order using the Merge Sort algorithm.
Explanation:
The Merge Sort algorit...read more
Implement Merge Sort algorithm to sort a sequence of numbers in non-descending order.
Divide the input array into two halves recursively until each array has only one element.
Merge the sorted halves to produce a completely sorted array.
Time complexity of Merge Sort is O(n log n).
Example: Input: [3, 1, 4, 1, 5], Output: [1, 1, 3, 4, 5]
Q41. Bipartite Graph Check
Determine if a given graph is bipartite. A graph is considered bipartite if its vertices can be divided into two disjoint sets, 'U' and 'V', such that every edge connects a vertex in 'U' t...read more
Check if a given graph is bipartite by dividing its vertices into two disjoint sets.
Create two sets 'U' and 'V' to divide the vertices
Check if every edge connects vertices from different sets
Use graph traversal algorithms like BFS or DFS to determine bipartiteness
Q42. Longest Substring Without Repeating Characters Problem Statement
Given a string S
of length L
, determine the length of the longest substring that contains no repeating characters.
Example:
Input:
"abacb"
Output...read more
Find the length of the longest substring without repeating characters in a given string.
Use a sliding window approach to keep track of the longest substring without repeating characters.
Use a hashmap to store the index of each character in the string.
Update the start index of the window when a repeating character is encountered.
Calculate the maximum length of the window as you iterate through the string.
Return the maximum length as the result.
Q43. Remove Duplicates from String Problem Statement
You are provided a string STR
of length N
, consisting solely of lowercase English letters.
Your task is to remove all duplicate occurrences of characters in the s...read more
Remove duplicate occurrences of characters in a given string.
Use a hash set to keep track of characters seen so far.
Iterate through the string and add non-duplicate characters to a new string.
Return the new string as the result.
Virtual memory allows the operating system to use a combination of RAM and disk space to simulate more memory than is physically available. Cache implementation involves storing frequently accessed data in a smaller, faster memory for quicker access.
Virtual memory allows programs to use more memory than physically available by swapping data between RAM and disk.
Cache implementation involves storing frequently accessed data in a smaller, faster memory for quicker access.
Exampl...read more
Q45. Binary search on rotated array
Binary search on rotated array involves finding a target element in a sorted array that has been rotated.
Find the pivot point where the array is rotated
Determine which half of the array the target element lies in
Perform binary search on the appropriate half of the array
Q46. ACID in dbms was asked
ACID is a set of properties that guarantee database transactions are processed reliably.
ACID stands for Atomicity, Consistency, Isolation, Durability.
Atomicity ensures that all operations in a transaction are completed successfully or none at all.
Consistency ensures that the database remains in a consistent state before and after the transaction.
Isolation ensures that multiple transactions can be executed concurrently without affecting each other.
Durability ensures that once ...read more
More about working at Samsung
Interview Process at ITC
Top Software Developer Intern Interview Questions from Similar Companies
Reviews
Interviews
Salaries
Users/Month