Q. Implement an LRU (Least Recently Used) Cache.
asked 2xmediumDesignTechnical2013-2021
Ans. Use a hash map plus a doubly linked list. The map gives O(1) access to cache nodes by key, and the list keeps usage order, with most recent at the front and least recent at the back. On get or put, move the node to the front. When capacity is exceeded, remove the back node.
Q. Explain pointers and dynamic memory allocation in C.
asked 2xeasyOOPTechnical2017-2020
Ans. Pointers are variables that store memory addresses, usually of other variables or heap-allocated objects. Dynamic memory allocation in C uses functions like malloc, calloc, realloc and free to request and release memory at runtime. The key detail is ownership: every successful allocation should be checked, used within bounds, and freed exactly once.
Q. Implement a Bit Array in C.
asked 1xmediumBit manipulationTechnical2014
Ans. Implement it as a struct holding the number of bits and a dynamically allocated array of unsigned words. Allocate enough words using ceiling division, then set, clear, toggle, and test a bit by computing its word index and bit offset and applying masks. Each operation is O(1), with O(n) bits of storage.
Q. What is object slicing in C++?
asked 1xmediumOOPTechnical2025
Ans. Object slicing in C++ happens when a derived object is copied into a base class object by value, so the derived-specific part is discarded. The result contains only the base subobject, losing derived data and behaviour. Avoid it by using references, pointers, or smart pointers when working polymorphically.
Q. Explain the structure hack in C.
asked 1xmediumCTechnical2013
Ans. The structure hack is a C technique for storing variable-length data at the end of a struct by declaring a final dummy array member and allocating extra memory. The important detail is that modern C supports this properly with a flexible array member, written as an incomplete array at the end of the struct.
Q. Find an element in a bitonic array.
asked 1xmediumBinary searchTechnical2020
Ans. Find the peak using binary search, then binary search the increasing left half and the decreasing right half for the target. The key detail is that comparisons differ on each side: normal binary search on the left, reversed binary search on the right. This takes O(log n) time and O(1) space.
Q. Design and implement a basic web crawler.
asked 1xmediumDesignTechnical2017
Ans. Use a queue for URLs to visit and a visited set to avoid repeats. Start with seed URLs, fetch each page, parse links, normalise them, filter by scope and robots.txt, then enqueue unseen links. Add rate limiting per host and retry handling. Time is proportional to fetched pages plus discovered links.
Q. Reverse a linked list in groups of size k.
asked 1xmediumLinked listsTechnical2024
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. Discuss and solve a graph traversal problem.
asked 1xmediumGraphsTechnical2024
Ans. Use breadth first search to find the shortest path in an unweighted graph from a start node to a target node. Store the graph as an adjacency list, keep a queue of nodes to visit, and mark visited nodes to avoid cycles. Track parents to rebuild the path. Time complexity is O(V + E).
Q. Explain structure padding and alignment in C.
asked 1xmediumCTechnical2013
Ans. Structure padding is extra unused memory the compiler inserts so each struct member is placed at an address matching its alignment requirement. This makes access efficient and ABI-compatible, but means sizeof a struct can exceed the sum of its fields. Member order matters, and padding may also be added at the end.
Q. Perform topological sorting of a graph using DFS.
asked 1xmediumGraphsOnline test2017
Ans. Run DFS on each unvisited vertex, and after visiting all its outgoing neighbours, push the vertex onto a stack or list. When all DFS calls finish, reverse that list to get the topological order. Use an adjacency list and visited state array. This works for DAGs in O(V + E) time and O(V) extra space.
Q. Maintain the k most frequently dialed phone numbers.
asked 1xmediumHashingTechnical2017
Ans. Use a hash map from phone number to count, plus a size k min heap containing the current top k numbers by count. On each dial, increment the count. If the number is in the heap, update and heapify. Otherwise insert or replace the heap minimum if its count is higher. Each update is O(log k).
Q. Print the vertical order traversal of a binary tree.
asked 1xmediumTreesTechnical2017
Ans. Use level order traversal while assigning each node a horizontal distance, with root at 0, left child minus 1 and right child plus 1. Store values in a map from distance to list. BFS preserves top to bottom order within each column. Print columns from smallest to largest distance. Time is O(n).
Q. Explain threads and their usage in operating systems.
asked 1xmediumOperating systemsHR2016
Ans. Threads are the smallest units of execution within a process, sharing the same memory space and resources while having their own stack and program counter. Operating systems use threads to run tasks concurrently, improve responsiveness, and use multiple CPU cores efficiently. The key issue is synchronisation, because shared data can cause race conditions.
Q. How would you optimize the space complexity of a trie?
asked 1xmediumData structuresTechnical2017
Ans. I would optimize a trie by avoiding fixed-size child arrays and compressing paths where possible. Use a hash map or sorted map for children when nodes are sparse, and use a compressed trie, or radix tree, to merge chains of single-child nodes into one edge. Lookups remain proportional to key length.
Q. How are ordered_maps implemented internally in C++ STL?
asked 1xmediumData structuresSystem design2025
Ans. Ordered maps in the C++ STL, such as std::map, are internally implemented as self-balancing binary search trees, typically red-black trees. The tree keeps keys in sorted order and rebalances after insertions and deletions. Search, insertion and deletion take logarithmic time, and iteration visits elements in key order.
Q. Explain or solve a problem based on trie data structures.
asked 1xmediumTreesTechnical2017
Ans. Use a trie to store strings character by character, where each node has links to children and a flag marking the end of a word. For insert and search, walk one character at a time, creating or following nodes. The key benefit is prefix handling, with time complexity O(L) for a word of length L.
Q. Rearrange a given linked list in-place in a specific order.
asked 1xmediumLinked listsTechnical2020
Ans. Find the middle with slow and fast pointers, reverse the second half in place, then merge the two halves alternately to get first, last, second, second-last, and so on. Use only pointer changes, not extra nodes or arrays. The time complexity is O(n) and the extra space is O(1).
Q. Compute the size of a structure in C (struct hack involved).
asked 1xmediumCOnline test2014
Ans. The size is the size of all fixed members plus any padding needed for alignment; the “struct hack” array at the end contributes only its declared compile-time size. With the old one-element hack, sizeof includes one element. With a C99 flexible array member, sizeof excludes the trailing array entirely. Allocate extra bytes separately for its contents.
Q. Print the nth Fibonacci number (n ≤ 20000) in hexadecimal form.
asked 1xmediumDynamic programmingOnline test2017
Ans. Compute Fibonacci iteratively using a big integer, then print that big integer in base 16. For languages without built-in big integers, store the number as limbs in base 2^32, repeatedly add the previous two values, and output the most significant limb normally, then remaining limbs as 8-digit hexadecimal blocks. Time is O(n^2).
Q. What is the critical section problem and what are its solutions?
asked 1xmediumOperating systemsTechnical2020
Ans. The critical section problem is coordinating concurrent processes or threads so only one enters shared-resource code at a time. A correct solution must ensure mutual exclusion, progress, and bounded waiting. Common solutions include mutex locks, semaphores, monitors, condition variables, and hardware-supported atomic operations such as test-and-set or compare-and-swap.
Q. Extend the phonebook design to support searching by phone number.
asked 1xmediumData structuresTechnical2014
Ans. Add a reverse index keyed by normalised phone number, mapping to the contact ID or a set of contact IDs. Keep it updated on create, update and delete alongside the name index. Lookup by phone number is then a hash table read, giving average O(1) time, with O(n) extra space.
Q. Divide a linked list into k parts and perform required operations.
asked 1xmediumLinked listsTechnical2024
Ans. Count the linked list length, compute each part size as n / k plus one extra node for the first n % k parts, then traverse and cut the next pointer after each part. Store the k heads in an array. This preserves order and runs in O(n) time with O(k) extra space.
Q. Explain the struct hack in C and how structure size is calculated.
asked 1xmediumCTechnical2014
Ans. The struct hack is an old C idiom where a structure ends with a one element array, then extra memory is allocated so that array can hold variable length data. Structure size is calculated from member sizes plus padding for alignment, including possible tail padding. Extra allocated bytes are not counted by sizeof.
Q. Find duplicates in a file containing 6-digit numbers in O(n) time.
asked 1xmediumHashingTechnical2014
Ans. Use a bitset indexed by the 6-digit value. Read each number once; if its bit is already set, it is a duplicate, otherwise set the bit. For values 000000 to 999999, the bitset needs 1,000,000 bits, about 125 KB. Time is O(n), memory is O(1) relative to file size.
Q. Explain networking sockets and how they are used for communication.
asked 1xmediumNetworkingHR2016
Ans. A networking socket is an endpoint that lets two programs send and receive data over a network. It is usually identified by an IP address, a port, and a protocol such as TCP or UDP. A server listens on a socket, a client connects to it, and both exchange bytes through that connection.
Q. Design a phonebook data structure to support searching by first name.
asked 1xmediumData structuresTechnical2014
Ans. Use a hash map from normalised first name to a list of phonebook entries. Each entry stores the full contact details, such as first name, surname and phone number. Insert by appending to the list for that name. Search is average O(1) to find the list, plus O(k) to return matches.
Q. Extend the phonebook design to support searching by last name as well.
asked 1xmediumData structuresTechnical2014
Ans. Add a secondary index on last name, kept in sync with the main phonebook records. Store each contact once with a unique contact ID, then map lastName to a set of IDs, or use a last-name trie if prefix search is required. Insert, update and delete must update both indexes. Exact lookup is O(1) average with a hash map.
Q. Design a stack that supports getMin() in O(1) time and O(1) extra space
asked 1xmediumStackTechnical2022
Ans. Use one stack plus a variable currentMin. When pushing a value smaller than currentMin, store an encoded value such as 2*x - currentMin and update currentMin to x. When popping an encoded value, restore the previous minimum as 2*currentMin - encoded. Push, pop, top and getMin are all O(1).
Q. Find the maximum sum from the root to a leaf node in a given n-ary tree.
asked 1xmediumTreesOnline test2017
Ans. Use depth first search and return each node’s value plus the maximum root to leaf sum among its children. A leaf returns its own value, and an empty tree can return 0 or negative infinity depending on the definition. Visit every node once, so time is O(n), with O(h) recursion stack space.
Q. Find duplicate digits in a 6-digit number in O(n) time and minimum space.
asked 1xmediumBit manipulationTechnical2017
Ans. Use a 10-bit mask to record which digits have been seen while scanning the number digit by digit. Extract each digit using modulo 10 and division by 10, or scan its string form. If the digit’s bit is already set, it is a duplicate. Time is O(n), space is O(1).
Q. How would you implement a dynamic array (similar to C++ STL vector) in C?
asked 1xmediumOOPSystem design2021
Ans. Implement it as a struct holding a pointer to a contiguous heap array, the current element count, and the allocated capacity. Allocate initially with malloc, append by writing at size and incrementing it, and when full grow capacity, usually doubling, with realloc. Indexing is O(1), append is amortised O(1), resize is O(n).
Q. Allocate an m x n 2D array in C such that it can be accessed as arr[i][j].
asked 1xmediumCOnline test2014
Ans. Allocate one contiguous block as a pointer to an array of n elements, for example conceptually “arr is a pointer to rows of n ints”. Then arr[i][j] works naturally because the compiler knows the row width. This uses one allocation, good locality, one free, and takes O(mn) space.
Q. Design a feature to show the most frequent calls list with at most k items.
asked 1xmediumHeapTechnical2014
Ans. Use a hash map to count calls by identifier, then keep a min heap of size k ordered by frequency to produce the most frequent calls. For each distinct call, push it if the heap has space, otherwise replace the smallest when its count is higher. This is O(n log k) time and O(m + k) space.
Q. Given a sorted integer array, convert it into a balanced Binary Search Tree.
asked 1xmediumTreesOnline test2014
Ans. Pick the middle element as the root, then recursively build the left subtree from the left half and the right subtree from the right half. This keeps the tree height balanced because each subtree gets roughly half the elements. Use recursion to create tree nodes. Time complexity is O(n), with O(log n) stack space.
Q. Explain deadlocks and process synchronization mechanisms in operating systems.
asked 1xmediumOperating systemsTechnical2016
Ans. A deadlock is when processes wait forever for resources held by each other, so none can continue. It usually requires mutual exclusion, hold and wait, no preemption, and circular wait. Process synchronization prevents race conditions using mechanisms such as mutexes, semaphores, monitors, condition variables, and locks to control access to shared data.
Q. Identify and implement a Fibonacci-based pattern by analyzing given test cases.
asked 1xmediumPatternsOnline test2024
Ans. Generate the Fibonacci sequence from the smallest required values, then map each test case output to those values according to the observed indexing or layout pattern. Store the sequence in an array or list to avoid recomputation. Use iterative generation with two previous numbers, giving O(n) time and O(n) space, or O(1) if only printing.
Q. Write C code using pointers and dynamic memory allocation with malloc and calloc.
asked 1xmediumOOPTechnical2024
Ans. Use malloc to allocate a pointer to a dynamic array, and calloc when you need the memory zero-initialised. Store the returned address in a typed pointer, check for NULL, use pointer arithmetic or indexing to access elements, then free the memory once. The data structure is a dynamic array, with O(1) element access.
Q. Implement a hash map class and explain hashing and collision resolution techniques
asked 1xmediumHashingSystem design2025
Ans. Implement it with an array of buckets, a hash function that maps keys to indices, and entries storing key, value pairs. For collisions, use separate chaining with a linked list or dynamic array per bucket, or open addressing. Average get, put and delete are O(1), but worst case is O(n) without resizing.
Q. Suggest a data structure to search in a sorted linked list in better than O(n) time.
asked 1xmediumLinked listsTechnical2013
Ans. Use a skip list, which is a linked list augmented with higher level forward pointers to skip over many nodes during search. It keeps elements sorted but allows search to move in large steps, then refine at lower levels. Search, insert and delete are O(log n) expected time, with extra pointer storage.
Q. Explain HashMap implementation details and different collision resolution techniques.
asked 1xmediumOOPTechnical2021
Ans. A HashMap stores key value pairs in an array of buckets, using a hash function to map each key to an index. Collisions are handled mainly by separate chaining, where each bucket holds a list or tree, or open addressing, where probing finds another slot. Good hashing and resizing keep average lookup, insert, and delete time constant.
Q. Modify the frequent calls design to handle ties while still maintaining only k items.
asked 1xmediumHeapTechnical2014
Ans. Define a deterministic tie breaker and include it in the heap ordering, so the structure always keeps exactly k items. Store counts in a hash map and keep a min heap of size k ordered by count first, then by tie rule, such as most recent call or lexicographic id. Updates cost O(log k).
Q. Explain the memory layout of a C program and where different types of variables are stored.
asked 1xmediumOperating systemsTechnical2020
Ans. A C program is typically laid out as text/code, read-only data, initialised data, BSS, heap and stack. Code goes in text, string literals and constants in read-only data, initialised globals and statics in data, zero-initialised globals and statics in BSS, malloc memory on the heap, and local automatic variables on the stack.
Q. Design a phone directory to store phone numbers and retrieve information based on the number.
asked 1xmediumDesignTechnical2017
Ans. Use a hash map or database table keyed by the normalised phone number, storing the associated contact or account details as the value. Normalise numbers to a canonical format, such as E.164, before storing or querying. Exact lookup, insert and delete are O(1) on average with a hash map, or indexed lookup in a database.
Q. Merge two arrays where the first array has enough empty space to accommodate the second array.
asked 1xmediumArraysTechnical2014
Ans. Merge them from the end of the first array, comparing the last real element of the first array with the last element of the second array. Put the larger value into the last free position and move backwards. This avoids overwriting data. It uses no extra data structure and runs in O(m + n) time.
Q. Design a stack that supports push, pop, and getMin operations in O(1) time and O(1) extra space
asked 1xmediumStackTechnical2021
Ans. Use one stack plus a variable min, storing encoded values when a new minimum is pushed. If x is below min, push 2*x - min and set min to x. On pop, if the stored value is below min, restore the old minimum as 2*min - stored. All operations are O(1).
Q. Which data structure would you use to implement string prediction/autocomplete as in mobile phones?
asked 1xmediumTreesTechnical2016
Ans. Use a Trie, also called a prefix tree, to implement autocomplete. Each node represents a character, and paths from the root form words, making prefix lookup efficient. Store word-end markers and optionally frequency or recency scores to rank suggestions. Lookup takes time proportional to the prefix length plus returned matches.
Q. Given a parent directory, how would you insert a new directory into your file system data structure?
asked 1xmediumTreesTechnical2016
Ans. Create a new directory node and attach it as a child of the given parent directory node. The key detail is how children are stored: with a hash map by name, check for an existing child with that name, then insert in average O(1) time. With a list, insertion is O(k).
Q. Identify and explain errors related to modifying read-only strings and constant pointers in C programs.
asked 1xmediumCTechnical2013
Ans. Errors occur when code writes to a string literal or tries to reassign a constant pointer. A string literal such as "hello" is read-only, so modifying its characters is undefined behaviour. With const char *p, the characters must not be changed through p. With char * const p, p cannot point elsewhere.
Q. Design a phonebook system that stores names and phone numbers and supports efficient prefix-based search.
asked 1xmediumDesignTechnical2017
Ans. Use a trie where each node represents a character and stores links to children plus references to contact records matching that prefix. Store full contact details in a separate database keyed by contact ID. Insert and lookup take O(k) for prefix length k, with results paginated and nodes optionally cached or sharded by leading characters.
Q. Find the mean and median of elements when numbers are dynamically added at runtime. Explain the approach.
asked 1xmediumHeapsTechnical2013
Ans. Maintain a running sum and count for the mean, and two heaps for the median. Store the lower half in a max heap and the upper half in a min heap, keeping their sizes balanced. On each insert, update sum and rebalance heaps. Mean is sum/count. Median is heap top or average of both tops. Insertion is O(log n).
Q. Predict the output of the following C program: int main(int argc, char *argv[]) { printf("%c", **++argv); }
asked 1xmediumCTechnical2013
Ans. It prints the first character of the first command-line argument. ++argv moves argv from argv[0], the program name, to argv[1]. *argv is therefore the first argument string, and **argv is its first character. If no argument is supplied, the program has undefined behaviour.
Q. Design a system like Zomato to answer queries such as which nearby restaurants are serving a particular dish.
asked 1xmediumDesignTechnical2020
Ans. Use a geospatial index for nearby restaurants and an inverted index from dish names to restaurant IDs, then intersect the two result sets. Store restaurant location, menu, availability, opening hours and ratings separately. The key detail is precomputing searchable dish tokens and geo cells so queries avoid scanning all restaurants.
Q. What are DFS and BFS? Which data structures are used to implement them, and print DFS and BFS of a given tree.
asked 1xmediumGraphsTechnical2014
Ans. DFS explores a tree as deep as possible before backtracking, while BFS explores level by level. DFS is implemented using recursion or a stack; BFS uses a queue. To print DFS, visit a node, then its children recursively. To print BFS, enqueue root, repeatedly dequeue, print, and enqueue children. Both take O(n) time.
Q. Write a search function to find a given directory by name across all directories in the file system structure.
asked 1xmediumTreesTechnical2016
Ans. Use depth first search from the root directory, checking each directory name and returning the match or collecting all matches. Use a stack, or recursion if the tree is not too deep. The time complexity is O(N), where N is the number of directories visited, and space is O(H) for recursion depth.
Q. How would you implement a frequently-called contacts list that returns the top K most frequently contacted people?
asked 1xmediumHeapTechnical2017
Ans. Maintain a hash map from contact to count, plus an ordered set sorted by count and contact id. On each contact, remove the old entry, increment the count, and reinsert it. To return top K, iterate from the highest counts. Updates cost O(log n), and reading top K costs O(k).
Q. Given a binary tree and two values a and b, find the shortest distance between the nodes containing values a and b.
asked 1xmediumTreesTechnical2013
Ans. Find the lowest common ancestor of the two nodes, then return the distance from that ancestor to a plus the distance from it to b. The key detail is that the shortest path must pass through the lowest common ancestor. Use DFS recursion. Time complexity is O(n), with O(h) recursion space.
Q. Modify the solution to find maximum root-to-leaf sum in an n-ary tree using an iterative approach instead of recursion.
asked 1xmediumTreesTechnical2017
Ans. Use an explicit stack to do depth first traversal, storing each node with the sum from the root to that node. Start with the root and its value, update the maximum only when a popped node is a leaf, and push each child with the updated sum. Time is O(n), space is O(h) to O(n).
Q. Explain shallow copy and deep copy.
asked 1xeasyOOPTechnical2024
Ans. A shallow copy creates a new outer object but keeps references to the same nested objects, while a deep copy creates a new object and recursively copies the nested objects too. The key difference is aliasing: changes to shared nested data affect both shallow copies, but not properly made deep copies.
Q. Discuss the impact of AI and automation in networking, covering different aspects such as efficiency, scalability, and future challenges.
asked 1xunknownCommunicationGroup discussion2023
Ans. A strong answer should use a real networking example, such as automated provisioning, anomaly detection, or self-healing operations. Emphasise measurable efficiency gains, improved scalability, and reduced human error, while recognising risks like model bias, security exposure, skills gaps, and over-reliance. Interviewers listen for balanced judgement, practical experience, and future awareness.
Showing 60 of 152 questions. Ranked by how often the same question came back across interviews.