
Samsung


100+ Samsung Interview Questions and Answers for Freshers
Q1. Reverse Alternate K Nodes Problem Statement
You are given a singly linked list of integers along with a positive integer 'K'. The task is to modify the linked list by reversing every alternate 'K' nodes of the ...read more
Reverse every alternate K nodes in a singly linked list of integers.
Traverse the linked list in groups of K nodes and reverse every alternate group.
Handle cases where the number of remaining nodes is less than K.
Ensure to properly link the reversed groups to maintain the integrity of the linked list.
Q2. What do you think is an area of improvement for you?
I need to improve my time management skills.
Prioritize tasks based on urgency and importance
Set realistic deadlines and stick to them
Avoid multitasking and focus on one task at a time
Use tools like calendars and to-do lists to stay organized
Q3. Trapping Rain Water Problem Statement
You are given a long type array/list ARR
of size N
, representing an elevation map. The value ARR[i]
denotes the elevation of the ith
bar. Your task is to determine the tota...read more
Calculate the total amount of rainwater that can be trapped between given elevations in an array.
Iterate through the array and calculate 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 entire array.
Q4. Shortest Path in a Binary Matrix Problem Statement
Given a binary matrix of size N * M
where each element is either 0 or 1, find the shortest path from a source cell to a destination cell, consisting only of 1s...read more
Find the shortest path in a binary matrix from a source cell to a destination cell consisting only of 1s.
Use Breadth First Search (BFS) algorithm to find the shortest path.
Initialize a queue with the source cell and keep track of visited cells.
Explore all 4 directions from each cell and update the path length accordingly.
Return the shortest path length or -1 if no valid path exists.
Q5. Write a C program that will COMPILE and RUN to reverse a string in-place
C program to reverse a string in-place
Use two pointers, one at the beginning and one at the end of the string
Swap the characters at the two pointers and move the pointers towards each other until they meet
Handle odd-length strings by leaving the middle character in place
Q6. Maximum Gold Collection from Gold Mine
Imagine a gold mine represented by a 2D matrix with dimensions 'N' by 'M', where 'N' is the number of rows and 'M' is the number of columns. Each cell in this matrix conta...read more
Find the maximum amount of gold a miner can collect from a gold mine by moving right, up diagonally, or down diagonally.
Use dynamic programming to keep track of the maximum gold collected at each cell.
At each cell, consider the maximum gold collected from the cell above, below, and to the left.
Add the current cell's gold value to the maximum gold collected from the adjacent cells to determine the maximum gold at the current cell.
Repeat this process for each cell in the matrix...read more
Q7. 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.
Q8. Find The Repeating And Missing Number Problem Statement
You are provided with an array nums
which contains the first N positive integers. In this array, one integer appears twice, and one integer is missing. Yo...read more
Given an array of first N positive integers with one number repeating and one missing, find the repeating and missing numbers.
Iterate through the array and keep track of the sum of elements and sum of squares to find the missing and repeating numbers.
Use a set to identify the repeating number and calculate the missing number based on the sum of elements.
Example: For nums = [1, 2, 3, 4, 4, 5], the repeating number is 4 and the missing number is 6.
Q9. Convert a Binary Tree to its Sum Tree
Given a binary tree of integers, convert it to a sum tree where each node is replaced by the sum of the values of its left and right subtrees. Set leaf nodes to zero.
Input...read more
Convert a binary tree to a sum tree by replacing each node with the sum of its left and right subtrees.
Traverse the tree in postorder fashion.
For each node, calculate the sum of its left and right subtrees and update the node value.
Set leaf nodes to zero.
Return the level order traversal of the modified tree.
Q10. Minimum Operation Needed to Convert to the Given String
You are given two strings str1
and str2
. Determine the minimum number of operations required to transform str1
into str2
.
Explanation:
An operation is def...read more
Determine the minimum number of operations needed to transform one string into another by moving characters to the end.
Iterate through each character in str1 and check if it matches the first character in str2.
If a match is found, calculate the number of operations needed to move the characters to the end.
Return the minimum number of operations needed for each test case, or -1 if transformation is not possible.
Q11. Binary Tree Diameter Problem Statement
You are given a Binary Tree, and you need to determine the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any ...read more
Find the diameter of a binary tree, which is the longest path between any two end nodes.
Traverse the tree to find the longest path between two nodes.
Use recursion to calculate the diameter of the tree.
Keep track of the maximum diameter found during traversal.
Example: For input 1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1, the diameter is 6.
Q12. 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 like (arr[i], arr[j]) and (arr[j], arr[i]) separately.
Q13. Count Subarrays with Given XOR Problem Statement
You are given an array of integers ARR
and an integer X
. Your task is to determine the number of subarrays of ARR
whose bitwise XOR is equal to X
.
Example:
Input...read more
Count the number of subarrays in an array whose XOR is equal to a given value.
Iterate through the array and keep track of XOR values and their frequencies using a hashmap.
For each element, calculate the XOR value with all previous elements and check if the XOR value equals the given X.
Use the hashmap to count the number of subarrays with XOR equal to X.
Time complexity can be optimized to O(N) using a hashmap to store XOR values and their frequencies.
Q14. Reach the Destination Problem Statement
You are given a source point (sx, sy) and a destination point (dx, dy). Determine if it is possible to reach the destination point using only the following valid moves:
- ...read more
The problem involves determining if it is possible to reach a destination point from a source point using specified moves.
Iterate through each test case and check if the destination point can be reached from the source point using the given moves.
Keep track of the current position and try all possible moves to reach the destination point.
Return true if the destination point is reachable, otherwise return false.
Q15. 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 greater than 0.
Use bitwise operations to determine if the integer is a power of two.
Return true if the integer is a power of two, otherwise return false.
Q16. Merge K Sorted Arrays Problem Statement
Given 'K' different arrays that are individually sorted in ascending order, merge all these arrays into a single array that is also sorted in ascending order.
Input
The f...read more
Merge K sorted arrays into a single sorted array.
Iterate through all arrays and merge them into a single array.
Use a priority queue to efficiently merge the arrays.
Ensure the final array is sorted in ascending order.
Q17. 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 operations.
Create a stack class with two queue data members.
Implement push(data) by enqueuing the data into one of the queues.
Implement pop() by dequeuing all elements from one queue to another until the last element is reached and return it.
Implement top() by dequeuing all elements from one queue to another until the last element is reached, return it, and then enqueue it back.
Implement size() by retur...read more
Q18. What are storage classes in C?Explain
Storage classes in C define the scope and lifetime of variables.
There are four storage classes in C: auto, register, static, and extern.
Auto variables are local to a block and have automatic storage duration.
Register variables are stored in CPU registers for faster access.
Static variables have a lifetime throughout the program and are initialized only once.
Extern variables are declared outside any function and can be accessed by any function in the program.
Q19. A piece of plain paper is torn into random number of pieces and how do you construct back the original paper?
Use jigsaw puzzle approach to reconstruct the paper.
Sort the pieces by edges and corners.
Identify patterns and colors to match adjacent pieces.
Use trial and error method to fit the pieces together.
Check for completeness and accuracy of the final paper.
Use computer vision and machine learning algorithms for automation.
Q20. Doctor Ninja's House Problem Statement
In a network of 'N' cities with 'M' paths connecting them, Doctor Ninja aims to purchase a house in a city 'X' such that it is possible to reach every other city from city...read more
Find the city from which all other cities can be reached in a network of cities connected by paths.
Identify the city 'X' from which all other cities can be reached either directly or indirectly.
Use depth-first search (DFS) to traverse the graph and find the mother vertex.
If multiple options for city 'X' exist, select the city with the smallest number.
If no such city exists, return -1.
Q21. which is faster x++ or ++x and why?
++x is faster than x++ because it increments the value before using it.
++x increments the value before using it, while x++ increments the value after using it.
++x is faster because it saves the overhead of creating a temporary variable.
In some cases, the difference in speed may be negligible and the choice between the two may depend on readability and coding standards.
Q22. Implement a Stack Using Two Queues
You are tasked with implementing a Stack data structure specifically designed to store integer data using two Queues. Utilize the inbuilt Queue for this purpose.
Function Requ...read more
Implement a Stack data structure using two Queues for integer data.
Use two Queues to simulate the Stack behavior.
Push elements by enqueueing them in one Queue.
Pop elements by dequeueing all elements from the first Queue to the second Queue, except the last one.
Top element can be retrieved by dequeuing all elements from the first Queue to the second Queue and then dequeuing the last element.
Size can be obtained by returning the size of the first Queue.
Check for isEmpty by chec...read more
Q23. LCA of Binary Tree Problem Statement
You are given a binary tree consisting of distinct integers and two nodes, X
and Y
. Your task is to find and return the Lowest Common Ancestor (LCA) of these two nodes.
The ...read more
Find the Lowest Common Ancestor of two nodes in a binary tree.
Traverse the binary tree to find the paths from the root to nodes X and Y.
Compare the paths to find the last common node, which is the Lowest Common Ancestor.
Implement a recursive function to find the LCA efficiently.
Handle edge cases such as when X or Y is the root node or when X or Y is not present in the tree.
Q24. Circle of Words Problem Statement
Given an array or list of words, determine whether the words can be rearranged to form a circle where the last character of one word matches the first character of the next.
In...read more
Check if given words can be rearranged to form a circle where the last character of one word matches the first character of the next.
Create a graph where each word is a node and there is an edge between two nodes if the last character of one word matches the first character of the next.
Check if the graph is strongly connected, meaning there is a path between every pair of nodes.
If the graph is strongly connected, return true; otherwise, return false.
Q25. Implement a Stack using Queues
Create a Stack data structure designed specifically to store integer data using two queues.
Explanation:
You need to implement a stack using two internal queues. You can utilize a...read more
Implement a Stack using Queues to store integer data with push, pop, top, size, and isEmpty functions.
Use two queues to simulate a stack, with one queue acting as the main stack and the other for temporary storage.
For push operation, enqueue the new element to the temporary queue, then dequeue all elements from the main queue to the temporary queue, and finally swap the queues.
For pop operation, dequeue the top element from the main queue.
For top operation, return the front e...read more
Q26. Write a program to insert a node in linked list
Program to insert a node in linked list
Create a new node with the given data
Set the next pointer of the new node to the next pointer of the previous node
Set the next pointer of the previous node to the new node
Q27. 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.
Q28. Rain Water Trapping Problem Statement
Given an array/list ARR
of size N
, representing an elevation map where each element ARR[i]
denotes the elevation of the i-th
bar. Your task is to calculate and print the to...read more
Calculate the total amount of rainwater that can be trapped between given elevations in an array.
Use two-pointer approach to keep track of left and right boundaries.
Calculate the trapped water by finding the minimum of maximum heights on left and right sides for each bar.
Sum up the trapped water for all bars to get the total amount of rainwater trapped.
Q29. Write a program to find loop in linked list
Program to find loop in linked list
Use two pointers, slow and fast, to traverse the linked list
If there is a loop, the fast pointer will eventually catch up to the slow pointer
To find the start of the loop, reset the slow pointer to the head and move both pointers at the same pace
Q30. Count Diagonal Paths
You are given a binary tree. Your task is to return the count of the diagonal paths to the leaf of the given binary tree such that all the values of the nodes on the diagonal are equal.
Inp...read more
Count the number of diagonal paths in a binary tree where all nodes on the diagonal have equal values.
Traverse the binary tree in a diagonal manner and keep track of nodes with equal values.
Use recursion to explore all possible diagonal paths in the tree.
Count the number of paths where all nodes on the diagonal have the same value.
Q31. 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'.
Q32. 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
Q33. 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)
Q34. 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.
The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence with increasing order.
Use dynamic programming to solve the LIS problem efficiently.
Maintain an array to store the length of the LIS ending at each element.
Iterate through the array and update the LIS length based on previous elements.
Example: For input [10, 22, 9, 33, 21, 50, 41, 60, 80], the LIS is [10, 22, 33, 50, 60, 80] with length 6.
Q36. 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.
Q37. wat is a null object? is it conceptual?
A null object is an object that does not have a value or reference to any object.
A null object is different from an object with a value of zero or an empty string.
It is often used to represent the absence of an object or value.
Null objects can be used to avoid null pointer exceptions in programming.
It is a conceptual idea in programming and computer science.
Q38. What are its features?Explain
Which software are you referring to?
Please specify the software you are asking about
Without context, it is impossible to answer this question
Q39. What are virtual functions?
Virtual functions are functions that can be overridden by derived classes.
Virtual functions are declared in a base class and can be overridden in a derived class.
They allow for polymorphism, where a derived class can be treated as its base class.
Virtual functions are called based on the actual object type, not the pointer or reference type.
They are declared using the 'virtual' keyword in the base class and optionally overridden using the 'override' keyword in the derived clas...read more
Q40. 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.
Q41. 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.
Q42. 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
Q43. Topological Sort Problem Statement
Given a Directed Acyclic Graph (DAG) consisting of V
vertices and E
edges, your task is to find any topological sorting of this DAG. You need to return an array of size V
repr...read more
Topological sort of a Directed Acyclic Graph (DAG) is finding an ordering of vertices where for every directed edge u -> v, u comes before v.
Use Depth First Search (DFS) to find the topological ordering of vertices in a DAG.
Start by visiting a vertex and recursively visit its neighbors, adding the vertex to the result after visiting all neighbors.
Maintain a visited array to keep track of visited vertices and a stack to store the topological ordering.
Once all vertices are visi...read more
Q44. 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.
Q45. 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
Q46. 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).
Q47. 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.
Q48. 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
Spiral order traversal of a binary tree involves printing nodes level by level alternating between left to right and right to left.
Start by pushing the root node into a queue.
While the queue is not empty, pop a node, print its value, and push its children into the queue.
For each level, alternate between printing nodes from left to right and right to left.
Repeat until all nodes are printed in spiral order.
Q50. 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
The task is to find all distinct triplets in 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.
Q51. 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
Q52. A pseudo code or solution(if you can) for solving the rubik's cube
A solution for solving the Rubik's cube
Use the layer-by-layer method
Solve the first layer cross
Solve the first layer corners
Solve the second layer
Solve the third layer cross
Solve the third layer corners
Orient the third layer corners
Permute the third layer corners
Permute the third layer edges
Q53. 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.
Q54. 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.
Q55. Build Max Heap Problem Statement
Given an integer array with N elements, the task is to transform this array into a max binary heap structure.
Explanation:
A max-heap is a complete binary tree where each intern...read more
The task is to transform an integer array into a max binary heap structure.
Create a max heap from the given array by rearranging elements
Ensure each internal node has a value greater than or equal to its children
Check if the transformed array represents a max-heap and output 1 if true, 0 if false
Q56. What is C++?
C++ is a high-level programming language used for developing system software, application software, device drivers, and video games.
C++ was developed by Bjarne Stroustrup in 1983.
It is an extension of the C programming language.
C++ supports object-oriented programming, generic programming, and low-level memory manipulation.
It is widely used in industries such as finance, gaming, and operating systems development.
Examples of popular software written in C++ include Microsoft Wi...read more
Q57. What is OOP?
OOP stands for Object-Oriented Programming, a programming paradigm that focuses on objects and their interactions.
OOP is based on the concepts of encapsulation, inheritance, and polymorphism.
It allows for modular and reusable code.
Examples of OOP languages include Java, C++, and Python.
Structure and union are both used to group different data types, but structure allocates memory for each member separately while union shares the same memory space for all members.
Structure allocates memory for each member separately, while union shares the same memory space for all members.
Structures are used when each member needs its own memory space and unions are used when only one member is accessed at a time.
Structures are typically larger in size compared to unions be...read more
Q59. 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
Q60. 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.
Q61. Maximum Product Subarray Problem Statement
Given an array of integers, determine the contiguous subarray that produces the maximum product of its elements.
Explanation:
A subarray can be derived from the origin...read more
Find the maximum product of a contiguous subarray in an array of integers.
Iterate through the array and keep track of the maximum and minimum product ending at each index.
Update the maximum product by considering the current element, the maximum product ending at the previous index multiplied by the current element, and the minimum product ending at the previous index multiplied by the current element.
Update the minimum product similarly.
Return the maximum product found durin...read more
Q62. Maximum Sum Rectangle Problem
Given an M x N matrix of integers ARR
, your task is to identify the rectangle within the matrix that has the greatest sum of its elements.
Input:
The first line of input contains a...read more
The task is to find the rectangle within a matrix that has the greatest sum of its elements.
Iterate through all possible rectangles within the matrix
Calculate the sum of each rectangle and keep track of the maximum sum
Return the maximum sum obtained from any rectangle within the matrix
Structure and union are both used to group different data types, but structure allocates memory for each member separately while union shares the same memory location for all members.
Structure allocates memory for each member separately, while union shares the same memory location for all members.
Structures are used when each member needs its own memory space, while unions are used when only one member is accessed at a time.
Structures are typically larger in size compared to ...read more
Q64. 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 all possible paths between any two nodes in the tree to find the maximum sum.
Q65. Rat in a Maze Problem Statement
You need to determine all possible paths for a rat starting at position (0, 0) in a square maze to reach its destination at (N-1, N-1). The maze is represented as an N*N matrix w...read more
Find all possible paths for a rat in a maze from source to destination.
Use backtracking to explore all possible paths in the maze.
Keep track of visited cells to avoid revisiting them.
Recursively move in all directions (up, down, left, right) until reaching the destination.
Return the list of valid paths sorted in alphabetical order.
Q66. 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
Q67. 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.
Q68. 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
Q69. 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
Q70. What is late binding
Late binding is a programming concept where the method or function to be executed is determined at runtime.
Also known as dynamic binding or runtime binding
Allows for greater flexibility in code execution
Commonly used in object-oriented programming languages
Example: virtual functions in C++
Q71. Tell about the spark architecture and data modelling
Spark architecture is a distributed computing system that provides high-level APIs for big data processing.
Spark architecture consists of a cluster manager, a distributed storage system, and a computing engine.
Data in Spark is represented as Resilient Distributed Datasets (RDDs) or DataFrames.
Spark supports various data models, including batch processing, streaming, machine learning, and graph processing.
Spark's architecture allows for in-memory data processing, which improve...read more
Q72. 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
Q73. 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.
Q74. 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
Q75. 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.
Q76. 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
Q77. 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.
Q78. 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
Q79. Explain logic of quick sort
Quick sort is a divide and conquer algorithm that sorts an array by partitioning it into two sub-arrays.
Choose a pivot element from the array
Partition the array around the pivot element
Recursively apply the above steps to the sub-arrays
Combine the sorted sub-arrays to get the final sorted array
Multitasking refers to the ability of an operating system to run multiple tasks concurrently, while multithreading involves executing multiple threads within a single process.
Multitasking allows multiple processes to run simultaneously on a single processor, switching between them quickly.
Multithreading enables a single process to execute multiple threads concurrently, sharing resources like memory and CPU.
Multitasking improves system efficiency by utilizing idle CPU time, wh...read more
Q81. 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]
DFS is a graph traversal algorithm that explores as far as possible along each branch before backtracking.
Start at a node and explore as far as possible along each branch before backtracking
Use a stack to keep track of nodes to visit
Mark visited nodes to avoid revisiting them
Recursive implementation is common
Q83. 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.
Q84. 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
Q85. Explain heap sort
Heap sort is a comparison-based sorting algorithm that uses a binary heap data structure.
Heap sort works by building a binary heap from the array to be sorted.
The largest element is then swapped with the root node and removed from the heap.
The heap is then restructured and the process is repeated until the array is sorted.
Heap sort has a time complexity of O(n log n) and is not stable.
It is often used in embedded systems and operating systems where memory is limited.
Q86. 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.
Q87. What is feedback in amplifiers? What are the types of feedback?
Feedback in amplifiers is a process of returning a portion of the output signal back to the input.
Feedback helps to improve the performance of amplifiers by reducing distortion and increasing stability.
There are two types of feedback: positive and negative.
Positive feedback increases the gain of the amplifier, while negative feedback decreases the gain.
Negative feedback is commonly used in amplifiers to improve linearity and reduce distortion.
Positive feedback is used in osci...read more
Q88. What are the basic role of JAVA in the development of software?
JAVA is a versatile programming language used for developing various software applications.
JAVA is platform-independent and can run on any operating system
It is object-oriented and supports multithreading
JAVA is widely used for developing web applications, mobile applications, and enterprise software
It provides a vast library of pre-built classes and APIs for developers to use
JAVA is also used for developing games, scientific applications, and financial applications
C++ supports polymorphism through virtual functions and inheritance.
C++ supports polymorphism through virtual functions and inheritance
Virtual functions allow a function to be overridden in a derived class
Base class pointers can point to derived class objects, allowing for dynamic binding
Example: class Animal { virtual void speak() { cout << 'Animal speaks'; } }; class Dog : public Animal { void speak() { cout << 'Dog barks'; } };
Example: Animal* a = new Dog(); a->speak(); //...read more
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
The four pillars of OOP are encapsulation, inheritance, polymorphism, and abstraction.
Encapsulation: Bundling data and methods that operate on the data into a single unit.
Inheritance: Allowing a new class to inherit properties and behaviors from an existing class.
Polymorphism: The ability for objects of different classes to respond to the same message in different ways.
Abstraction: Hiding the complex implementation details and showing only the necessary features of an object.
Yes, a singleton class is a class that can only have one instance created.
Ensure the constructor is private to prevent external instantiation.
Provide a static method to access the single instance.
Use a static variable to hold the single instance.
Example: class Singleton { private static Singleton instance = new Singleton(); private Singleton(){} public static Singleton getInstance() { return instance; }}
Q93. Difference between an embedded system and an IOT device??
Embedded systems are standalone devices with fixed functionality, while IoT devices are connected to the internet and can be remotely controlled.
Embedded systems are designed for specific tasks and have limited processing power and memory.
IoT devices are connected to the internet and can be controlled remotely through a network.
Embedded systems are often used in industrial and automotive applications, while IoT devices are used in smart homes, wearables, and other consumer ap...read more
Android is a mobile operating system developed by Google, based on the Linux kernel and designed primarily for touchscreen devices.
Developed by Google
Based on Linux kernel
Designed for touchscreen devices
Q95. Given two polynomials as linked lists, return a linked list which represents the product of two polynomials
The function takes two polynomials represented as linked lists and returns a linked list representing their product.
Traverse both linked lists and multiply the corresponding coefficients of each term
Create a new linked list to store the product terms
Keep track of the current term in the product linked list and update it as you multiply
Handle cases where the product of coefficients is zero
A process in an operating system is an instance of a program that is being executed.
A process is a unit of execution within an operating system.
Each process has its own memory space, resources, and state.
Processes can communicate with each other through inter-process communication.
Examples of processes include web browsers, word processors, and media players.
Q97. Is sale down what should we do to increase the sale ?
To increase sales, we need to analyze the market, identify customer needs, improve product quality, and implement effective marketing strategies.
Analyze the market to identify trends and competition
Identify customer needs and preferences
Improve product quality and features
Implement effective marketing strategies such as targeted advertising and promotions
Provide excellent customer service to retain existing customers and attract new ones
Q98. Difference between an FIR and IIR filter??
FIR filters have finite impulse response while IIR filters have infinite impulse response.
FIR filters have a linear phase response while IIR filters do not necessarily have a linear phase response.
FIR filters are always stable while IIR filters may not be stable depending on the coefficients used.
FIR filters have a fixed number of coefficients while IIR filters have a variable number of coefficients.
Examples of FIR filters include moving average filters and low-pass filters w...read more
Q99. Difference between an amplifier and an oscillator.
Amplifier increases the amplitude of a signal while oscillator generates a periodic signal.
Amplifier is used to increase the strength of a signal without changing its frequency.
Oscillator generates a periodic signal with a specific frequency.
Amplifiers are used in audio systems, power amplifiers, and RF amplifiers.
Oscillators are used in radio transmitters, clocks, and electronic musical instruments.
Q100. Given a boolean 2D matrix, find whether there is path from (0,0) to (i,j) and if there is one path, return the minimum no of steps needed, else return -1
Find minimum steps from (0,0) to (i,j) in boolean 2D matrix
Use Breadth First Search (BFS) to find the shortest path
Keep track of visited cells to avoid revisiting
Return -1 if no path is found
More about working at Samsung







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

Top Interview Questions from Similar Companies





