Q. Explain Object-Oriented Programming (OOPS) concepts in detail
asked 2xmediumOOPTechnical2017
Ans. Object-oriented programming organises software as objects that combine data and behaviour. A class is a blueprint, and an object is its instance. Encapsulation hides internal state behind methods. Abstraction exposes only essential details. Inheritance reuses and extends behaviour. Polymorphism lets the same interface work with different implementations.
Q. Measuring Block puzzle.
asked 1xmediumLogical reasoningTechnical2021
Ans. Break the block into 1, 3, 9 and 27 unit pieces. With a balance scale, each piece can go on the same pan, the opposite pan, or be unused. That gives balanced ternary combinations, covering every whole weight from 1 to 40, since 1 plus 3 plus 9 plus 27 equals 40.
Q. Reverse a linked list in groups of K.
asked 1xmediumLinked listsOnline test2019
Ans. Reverse each block of K nodes by iterating through the list, reversing K links at a time, and connecting the previous block’s tail to the new head. Use three pointers for reversal and keep track of the previous group tail. If fewer than K nodes remain, usually leave them unchanged. Time is O(n), space is O(1).
Q. Check whether a binary tree is symmetric
asked 1xmediumTreesTechnical2017
Ans. A binary tree is symmetric if its left and right subtrees are mirror images. Compare pairs of nodes: left child of one with right child of the other, and right child with left. If both are null they match, if one is null or values differ they fail. Time is O(n), space is O(h) recursively.
Q. Check whether a binary tree is a Sum Tree
asked 1xmediumTreesTechnical2019
Ans. Use a postorder traversal to verify that every non-leaf node equals the sum of values in its left and right subtrees. For each node, return both whether its subtree is valid and the subtree sum. A null node has sum 0, and a leaf is valid. Time is O(n), with O(h) recursion space.
Q. Implement problems using DFS and recursion
asked 1xmediumGraphsOnline test2017
Ans. Use recursion to explore one path fully before backtracking, marking each node or cell as visited to avoid cycles. For graphs, store neighbours in an adjacency list; for grids, try four or eight directions. The time complexity is usually O(V + E) for graphs or O(rows × columns) for grids.
Q. Reverse a linked list in groups of size 2.
asked 1xmediumLinked listsOnline test2017
Ans. Reverse the linked list by swapping every pair of adjacent nodes. Use a dummy node before the head, then repeatedly adjust pointers for prev, first and second nodes in each pair. Move prev forward after each swap. If one node remains at the end, leave it unchanged. Time is O(n), space is O(1).
Q. Explain BST search operation and BST Iterator
asked 1xmediumTreesTechnical2017
Ans. BST search compares the target with the current node, moves left if smaller, right if larger, and stops when found or null, taking O(h) time. A BST Iterator usually simulates inorder traversal using a stack of left nodes, giving sorted values with next in O(1) amortised time and O(h) space.
Q. Print all root-to-leaf paths of a binary tree
asked 1xmediumTreesTechnical2019
Ans. Do a depth first traversal, keeping the current path from the root to the current node. Add each visited node to a list; when you reach a leaf, print the list. After returning from a child, remove the node to backtrack. Time is O(n), excluding output size, and space is O(h).
Q. Reverse a linked list in groups of given size
asked 1xmediumLinked listsOnline test2019
Ans. Reverse each group of k nodes by iterating through the list and reversing pointers within the current group, then connect the previous group’s tail to the new head. Use only node pointers, not an extra data structure. If fewer than k nodes remain, usually leave them unchanged. Time complexity is O(n), space is O(1).
Q. Traverse a given m x n matrix in spiral order.
asked 1xmediumArraysTechnical2021
Ans. Traverse the matrix by maintaining four boundaries: top, bottom, left, and right, and repeatedly visit the top row, right column, bottom row, and left column in order. After each side, move that boundary inward. Stop when boundaries cross. Use a result list. Time complexity is O(mn), space is O(1) excluding output.
Q. Reverse a linked list in groups of given size k.
asked 1xmediumLinked listsOnline test2019
Ans. Reverse each block of k nodes by rewiring next pointers, then connect the previous block’s tail to the new head of the reversed block. Use three pointers to reverse a block in place, and first check that k nodes remain if partial groups should stay unchanged. Time complexity is O(n), space complexity is O(1).
Q. Perform vertical order traversal of a binary tree
asked 1xmediumTreesTechnical2019
Ans. Use BFS while assigning each node a column index, with root at 0, left child at column minus 1 and right child at column plus 1. Store values in a map from column to list. Finally output lists from smallest to largest column. Time is O(n log n) with an ordered map.
Q. Find the minimum element in a rotated sorted array.
asked 1xmediumBinary searchTechnical2021
Ans. Use binary search to find the point where the sorted order restarts. Keep two pointers, left and right, and compare the middle value with the right value. If middle is greater, the minimum is to the right; otherwise it is at middle or to the left. This uses no extra data structure and runs in O(log n).
Q. Construct a 16:1 multiplexer using 4:1 multiplexers.
asked 1xmediumDigital logicOnline test2017
Ans. Use five 4:1 multiplexers. Connect the 16 inputs into four groups of four, each feeding one first-stage 4:1 multiplexer controlled by the two least significant select lines. Feed those four outputs into a fifth 4:1 multiplexer controlled by the two most significant select lines.
Q. Explain and implement Topological Sorting of a graph
asked 1xmediumGraphsTechnical2017
Ans. Topological sorting orders the vertices of a directed acyclic graph so every edge u to v places u before v. Implement it with Kahn’s algorithm: store adjacency lists and an indegree array, push all zero-indegree vertices into a queue, remove them, and reduce neighbours’ indegrees. If not all vertices are output, a cycle exists. Time is O(V + E).
Q. Implement your own Binary Search Tree (BST) Iterator
asked 1xmediumTreesOnline test2017
Ans. Use an explicit stack to simulate an inorder traversal, so the iterator returns BST values in sorted order. Initialise by pushing the root and all its left children. next pops the top node, then pushes the left path of its right child. hasNext checks the stack. Space is O(h), next is amortised O(1).
Q. Find the kth minimum element in a Binary Search Tree.
asked 1xmediumTreesTechnical2021
Ans. Do an inorder traversal of the BST and return the node visited kth, because inorder visits keys in sorted ascending order. Use a recursive counter or an explicit stack, stopping as soon as the kth node is reached. The time complexity is O(h + k), and the space complexity is O(h).
Q. Implement an efficient algorithm to compute pow(x, n).
asked 1xmediumMathTechnical2017
Ans. Use exponentiation by squaring. Keep a result initially 1, repeatedly square x and halve n; when the current exponent bit is odd, multiply the result by x. For negative n, compute using the absolute exponent and return its reciprocal. This runs in O(log |n|) time and O(1) space.
Q. How would you check connectivity if the graph is directed?
asked 1xmediumGraphsTechnical2017
Ans. For a directed graph, I would usually check strong connectivity by running DFS or BFS from any vertex, then doing the same on the graph with all edges reversed. If every vertex is reached in both traversals, the graph is strongly connected. This takes O(V + E) time.
Q. What are virtual functions and virtual destructors in C++?
asked 1xmediumOOPTechnical2021
Ans. Virtual functions in C++ are member functions declared with virtual so calls are resolved at runtime based on the actual object type, enabling polymorphism. A virtual destructor ensures the derived destructor runs when deleting an object through a base-class pointer. Base classes meant for polymorphic use should almost always have a virtual destructor.
Q. Detect a cycle in a directed graph and an undirected graph.
asked 1xmediumGraphsTechnical2021
Ans. Use DFS: for a directed graph, track visited nodes and a recursion stack; reaching a node already in the current stack means a cycle. For an undirected graph, track visited nodes and the parent; reaching a visited neighbour that is not the parent means a cycle. Time complexity is O(V + E).
Q. Given an N-ary tree, find all paths from root to leaf nodes.
asked 1xmediumTreesTechnical2019
Ans. Use depth first search with backtracking from the root, keeping a current path list. Add the current node, and if it has no children, copy the path into the result. Otherwise recurse on each child, then remove the node when returning. Time complexity is O(total path output size), with O(height) extra recursion space.
Q. Explain the Knuth-Morris-Pratt (KMP) string matching algorithm
asked 1xmediumStringsTechnical2017
Ans. KMP finds all occurrences of a pattern in a text in linear time by avoiding repeated comparisons after a mismatch. It first builds an LPS table, which stores the longest proper prefix that is also a suffix for each pattern prefix. During matching, it uses this table to shift the pattern without moving the text pointer backwards.
Q. Given two coordinates, determine whether the two lines intersect
asked 1xmediumGeometryTechnical2019
Ans. Use the orientation test with cross products to decide whether two line segments intersect. For segments AB and CD, they intersect if A and B are on different sides of CD and C and D are on different sides of AB, including collinear overlap cases. This runs in constant time, O(1).
Q. Count the total number of squares and rectangles on a chessboard.
asked 1xmediumLogical reasoningOnline test2017
Ans. Choose any two vertical grid lines and any two horizontal grid lines. A chessboard has 9 lines each way, so the number of rectangles is C(9,2) × C(9,2) = 36 × 36 = 1296. This includes squares. The squares alone are 1² + 2² + … + 8² = 204.
Q. Design a computer system with intelligence for the game Tic-Tac-Toe.
asked 1xmediumDesignTechnical2019
Ans. Represent the board as a 3 by 3 array and choose moves using minimax, because Tic-Tac-Toe has a small complete game tree. The system should validate moves, detect wins or draws, generate legal moves, score terminal states as win, loss or draw, and pick the move with the best guaranteed outcome.
Q. Can a function be called before main() in C++? Explain possible ways.
asked 1xmediumCppTechnical2017
Ans. Yes, a function can run before main() during static initialisation. Common ways are calling it in the initialiser of a global or namespace-scope variable, or from the constructor of a global object. Some compilers also provide extensions such as constructor attributes, but those are not standard C++.
Q. Re-solve written test coding questions considering all boundary cases
asked 1xmediumGeneralTechnical2017
Ans. Re-solve each coding question by first clarifying input limits, expected output, and invalid or empty inputs. Then choose the simplest correct approach, state the data structure, and check boundary cases such as zero size, one element, duplicates, negatives, maximum values, sorted input, and all equal values. Finally, give time and space complexity.
Q. Analyze time complexity of different approaches and justify the optimal one
asked 1xmediumComplexity analysisTechnical2017
Ans. Start with the simplest correct approach, usually brute force, and state its cost. Then show what repeated work it does and how a better data structure or algorithm removes it. The optimal approach is the one that matches the lower bound, such as visiting each input item once, giving O(n) when every item must be inspected.
Q. Explain templates in C++ and write the syntax for declaring a generic class.
asked 1xmediumOOPTechnical2021
Ans. Templates in C++ let you write generic functions or classes where the type is supplied later, allowing the same code to work with different data types. A generic class is declared by placing a template parameter list before the class, typically using template, angle brackets, typename or class, then the class definition.
Q. Given a BST, print all nodes which do not have siblings in preorder traversal.
asked 1xmediumTreesOnline test2019
Ans. Traverse the tree in preorder and print a child whenever its parent has exactly one child. For each node, if only the left child exists, print the left child; if only the right child exists, print the right child. Then recurse left and right. The BST property is irrelevant. Time is O(n), stack is O(h).
Q. Solve coding problems based on strings using optimal time and space complexity
asked 1xmediumStringsOnline test2017
Ans. Use a linear scan with the right data structure, usually a hash map, set, stack, two pointers, or trie, depending on the string task. Track only the needed state, such as character counts, last seen positions, or window bounds. Most optimal string solutions run in O(n) time with O(k) space.
Q. Given a logic circuit, identify the logic it represents and draw its truth table.
asked 1xmediumDigital logicOnline test2017
Ans. The circuit’s logic is found by labelling each gate output, writing the Boolean expression from inputs to final output, then evaluating every input combination in a truth table. For n inputs, list 2^n rows, compute intermediate columns if needed, and fill the final output column from the gate operations.
Q. For a given node in a binary tree, print its parent and sibling node if they exist.
asked 1xmediumTreesTechnical2019
Ans. Traverse the tree while keeping each node’s parent, and when the target node is found, print that parent and the parent’s other child as the sibling. If the target is the root, it has no parent or sibling. Use DFS recursion or BFS with a queue. Time complexity is O(n), with extra space O(h) for DFS.
Q. Given an unsorted array, find the length of the longest contiguous subarray product.
asked 1xmediumArraysOnline test2019
Ans. Track the longest subarray ending at each index with positive and negative product, and return the best positive length seen. For each number, update positive and negative lengths; swap roles on a negative value, and reset both on zero. This single pass uses constant extra space and runs in O(n) time.
Q. Given a graph problem, design an algorithm, handle all base cases, and write the code
asked 1xmediumGraphsTechnical2017
Ans. Model the graph with an adjacency list, validate empty or single-node inputs first, then choose BFS or DFS for traversal, shortest path in unweighted graphs, or Dijkstra for weighted non-negative graphs. Track visited nodes, parents or distances as needed. Time complexity is usually O(V + E), or O((V + E) log V) with Dijkstra.
Q. Reverse the words of a string in O(1) extra space (e.g., "i am a boy" → "boy a am i").
asked 1xmediumStringsOnline test2017
Ans. Reverse the whole character array, then reverse each word in place. For “i am a boy”, full reversal gives “yob a ma i”, and reversing characters inside each word gives “boy a am i”. This uses two pointers, O(n) time, and O(1) extra space if the string is mutable.
Q. Find the path with minimum cost in a matrix from top-left corner to bottom-right corner
asked 1xmediumDynamic programmingOnline test2017
Ans. Use dynamic programming: store the minimum cost to reach each cell from the top-left. Set the first cell to its matrix cost, fill the first row and column from their only possible predecessor, then each other cell takes its cost plus the minimum of top and left. The answer is the bottom-right value. Time is O(mn).
Q. How do virtual functions work internally in C++? Explain VTABLE, VPTR, and compiler role.
asked 1xmediumOOPTechnical2017
Ans. Virtual functions work through dynamic dispatch using a VTABLE and a VPTR. For each polymorphic class, the compiler creates a VTABLE containing addresses of virtual function implementations. Each object stores a hidden VPTR pointing to its class VTABLE. When a virtual function is called through a base pointer or reference, the compiler generates lookup code through the VPTR.
Q. Given a matrix M where M(i,j)=1 if i is the parent of j, construct the corresponding tree.
asked 1xmediumTreesTechnical2021
Ans. Create one tree node per index, then scan the matrix and whenever M(i,j) is 1, attach node j as a child of node i and record that j has a parent. After the scan, the node with no recorded parent is the root. Use an array of nodes and parent flags. Time complexity is O(n²).
Q. Optimize counting bit changes in a 32-bit integer by reducing comparisons using extra space.
asked 1xmediumBit manipulationTechnical2015
Ans. Use a lookup table to precompute bit-change counts for all 8-bit values, then split the 32-bit integer into four bytes and sum their stored counts. Add three comparisons for the byte boundaries, between bit 7 and bit 8, and so on. This uses extra space, but runs in constant time.
Q. How would you search if both rows and columns of the 2D array are sorted in descending order?
asked 1xmediumArraysTechnical2017
Ans. Start at the top right element and do a staircase search. If the current value equals the target, return found. If it is smaller than the target, move left because values increase to the left. If it is larger, move down because values decrease downwards. This takes O(rows + columns) time.
Q. Given a number and its index, determine if it is a valid index for that number in a Sudoku game
asked 1xmediumArraysTechnical2019
Ans. Convert the index to row and column, then check whether the same number already exists in that row, that column, or the corresponding 3 by 3 box. If none contain it, the index is valid for that number. Use the board as a 2D array; this takes constant time for Sudoku.
Q. Given two arrays of sizes m and n (m >> n), find the common elements using an optimal algorithm.
asked 1xmediumArraysOnline test2017
Ans. Store the smaller array in a hash set, then scan the larger array and report elements found in the set. This gives expected O(m + n) time and O(n) extra space, which is optimal for unsorted arrays because every element may need to be inspected. Use an output set if duplicates must be avoided.
Q. Find the inorder successor of a node in a Binary Search Tree where each node has a parent pointer.
asked 1xmediumTreesOnline test2017
Ans. The inorder successor is the next larger node in the BST. If the node has a right child, return the leftmost node in its right subtree. Otherwise, move up through parent pointers until you find an ancestor for which the current node is in the left subtree. That ancestor is the successor. Time is O(h), space is O(1).
Q. Given jobs with start time, end time, and CPU load, find the maximum CPU load at any time interval.
asked 1xmediumArraysTechnical2019
Ans. Sort the jobs by start time, then scan them while keeping a min heap of active jobs ordered by end time. Before adding a job, remove all jobs whose end time is not after its start and subtract their loads. Add the new load, update the maximum. Time complexity is O(n log n).
Q. Print the level number along with each node while performing level order traversal of a binary tree.
asked 1xmediumTreesTechnical2019
Ans. Use a queue for breadth first traversal, storing each node together with its level number. Start by pushing the root with level 0 or 1, depending on convention. Repeatedly pop the front, print the node value and level, then push its children with level plus one. Time is O(n), space is O(w).
Q. Given a 2D array M where M[i][j] = 1 indicates i is the parent of j, construct the corresponding tree.
asked 1xmediumTreesOnline test2017
Ans. Create one tree node for each index, then scan the matrix and whenever M[i][j] is 1, add node j as a child of node i. Keep a hasParent array and mark j true for each such edge. After the scan, the root is the only node not marked. Time complexity is O(n²), space is O(n).
Q. Given a number n, find the nearest smaller and greater numbers having the same number of set bits as n.
asked 1xmediumBit manipulationOnline test2017
Ans. Find the next greater by moving the rightmost non-trailing zero left of a block of ones, then place the remaining ones at the far right; find the next smaller symmetrically by moving the rightmost non-trailing one down and packing ones just to its left. This uses bit manipulation only, runs in O(number of bits) time and O(1) space.
Q. Search for a key in a 2D array where rows are sorted in ascending order and columns in descending order.
asked 1xmediumArraysTechnical2017
Ans. Start at the top left element and eliminate one row or column at each step. If the key is larger, move right because rows increase. If the key is smaller, move down because columns decrease. Stop when found or outside the matrix. This uses no extra data structure and runs in O(rows + columns) time.
Q. What is the static keyword in C++ and how can non-static variables be accessed inside a static function?
asked 1xmediumOOPTechnical2021
Ans. In C++, static gives a variable static storage duration or makes a class member belong to the class rather than each object. A static member function has no this pointer, so it cannot directly access non-static members. To access them, it must use an object, reference, or pointer to an instance.
Q. Given a binary tree, count the number of subtrees where all nodes in that subtree have the same data value.
asked 1xmediumTreesTechnical2019
Ans. Use a postorder DFS and count a subtree when both children are univalue subtrees and their values, if present, match the current node’s value. Return to the parent whether the current subtree is univalue. A null child counts as valid. This visits each node once, uses recursion stack space, and runs in O(n) time.
Q. Given n distinct integers and inequality signs between boxes, place the numbers to satisfy all inequalities.
asked 1xmediumGreedyTechnical2021
Ans. Model the boxes as a directed graph and use topological sorting. For each inequality A < B, add an edge from A to B, then take any topological order and assign the sorted integers in increasing order along it. If the graph has a cycle, no valid placement exists. Time is O(n + m).
Q. Given 100 balls with one defective ball and a balance, find the minimum number of steps to identify the defective ball.
asked 1xmediumLogical reasoningTechnical2021
Ans. Five weighings are enough, and four cannot be enough. Each balance weighing has three outcomes, so four weighings distinguish only 81 outcomes. If the ball may be heavier or lighter, there are 200 cases. Use a five-weighing ternary coding scheme, placing coded groups left, right, or off each time. The outcome pattern identifies the ball.
Q. Write a function that returns a different string every time it is called, even when called simultaneously across different machines and processors.
asked 1xmediumDistributed systemsTechnical2015
Ans. Return a generated ID string made from a unique machine identifier, the current timestamp, and an atomic per-machine sequence counter. The critical detail is that machine identifiers must never overlap. For calls in the same timestamp tick, increment the counter atomically. Store only the counter and last timestamp. Time complexity is O(1).
Q. Design a traffic signaling system and compute the average speed of vehicles; implement the solution in code
asked 1xhardDesignSystem design2017
Ans. Use signal controllers with road sensors that emit vehicle id, timestamp and location events, then compute speed from the time taken between two known points. Keep a hash map from vehicle id to its latest detection and update rolling totals per road segment. Each event is processed in O(1) time, with O(n) storage for active vehicles.
Q. What are storage classes in C++?
asked 1xeasyOOPTechnical2021
Ans. Storage classes in C++ define an object’s lifetime, visibility, and linkage. The main specifiers are static, extern, thread_local, and mutable. Historically, auto and register were also storage class specifiers, but auto now means type deduction and register is obsolete. The key idea is how long data exists and where it can be accessed.
Q. What is a virtual function in C++?
asked 1xeasyOOPTechnical2017
Ans. A virtual function in C++ is a member function declared with virtual so calls are resolved at runtime based on the actual object type. This enables polymorphism: a base class pointer or reference can call an overridden derived class method. Destructors should often be virtual in polymorphic base classes.
Q. Answer behavioral questions assessing professional conduct
asked 1xunknownProfessional behaviorSystem design2017
Ans. Pick a real workplace situation where your conduct affected trust, fairness, confidentiality, safety, or accountability. Emphasise the standard you recognised, the action you took, and how you handled pressure or conflict. Interviewers listen for judgement, honesty, respect for others, ownership of mistakes, and consistency with company values.
Showing 60 of 109 questions. Ranked by how often the same question came back across interviews.