Practice real software engineering interview questions, filterable by company, difficulty, and keywords.
Algorithms
Given two sorted integer arrays `nums1` and `nums2`, return the `k` pairs with the smallest sums. Each pair consists of one element from `nums1` and one element from `nums2`. For a pair `[nums1[i], nums2[j]]`, its sum is `nums1[i] + nums2[j]`. Return up to `k` pairs with the smallest sums. If there are fewer than `k` possible pairs, return all available pairs.
Object-Oriented Design
Design an object-oriented restaurant ordering and pricing system. The system should support multiple types of menu items, with `Pizza` as one of the core items. A pizza consists of a `Crust`, a `Size`, and zero or more `Topping` objects. Each crust has a base price, each size has a price multiplier, and each topping has its own price. The pizza price should be calculated as `Price = (base_price + sum(toppings_prices)) * size_multiplier`. The design should be extensible so that new sizes, toppings, or menu item types can be added without modifying the existing pricing and ordering logic. The system should also use appropriate object-oriented principles to separate responsibilities and avoid hard-coded conditional logic.
Hash Table
Given an absolute root path, recursively traverse all files under the directory. Files are considered duplicates when their complete contents are identical, regardless of file name, file extension, or file path. Group files with identical contents together and return all groups, including groups containing only one unique file. The input provides two helper functions: `listFolder(path)` returns all items directly under the current path, and `isFolder(path)` determines whether a path is a directory. The solution should recursively traverse the directory tree, generate a content signature for each file, and group files with the same signature. The key engineering requirement is that large files should not be fully loaded into memory. A production-quality solution should use file size as an initial filter, calculate hashes incrementally with streaming reads, and optionally perform byte-level comparison when files have the same size and hash.
Graph
Given a maze represented as a 2D grid, where an empty space `' '` represents a walkable cell and `'X'` represents an obstacle, find the shortest number of steps from a given start position to a given destination position. You can move between adjacent walkable cells in four directions: up, down, left, and right. Return the minimum number of steps required to reach the destination. If the destination cannot be reached, return the corresponding failure value defined by the interviewer. The maze should be treated as an unweighted graph, where each walkable cell represents a node and each valid movement represents an edge with equal cost.
Object-Oriented Design
Design a restaurant ordering and pricing system that supports different types of menu items. A Pizza consists of a crust, a size, and zero or more toppings. The system should calculate the final price dynamically while remaining easy to extend when new sizes, toppings, crusts, or menu item types are introduced. The initial pricing formula is: `Price = (base_price + sum(toppings_prices)) × size_multiplier` The design should avoid hard-coded strings and primitive values for domain concepts such as size, crust, and toppings. The system should also support additional menu items such as Pasta through a common `MenuItem` abstraction.
Machine Learning
You are given a feature matrix `X` containing continuous-valued samples and a label vector `y`. Part 1: Binary Classification Assume `y` contains two classes, `0` and `1`. Build a parameterized logistic regression model and implement the parameter estimation procedure using Maximum Likelihood Estimation. The implementation should compute the sigmoid function, binary cross-entropy loss, and gradients, then optimize the model parameters using gradient descent. Part 2: Multiclass Classification Assume `y` contains multiple classes such as `0`, `1`, and `2`. Build a Gaussian generative classifier that models the class prior probability and the conditional distribution of each feature given a class. Estimate the model parameters from the training data and use the resulting posterior probabilities to predict the class of new samples. The implementation should not rely on high-level machine learning libraries such as `sklearn`. Use basic mathematical operations and numerical computation primitives. The implementation should also consider numerical stability, including probability underflow, exponential overflow, and zero variance.
Graph
You are given a directed, weighted graph representing a network. Starting from node `k`, determine the minimum time required for a signal to reach every node. If there is at least one node that cannot be reached from `k`, return `-1`. Otherwise, return the maximum of the minimum travel times to all nodes.
Sliding Window
Given a circular necklace represented by a string `necklace`, each character is either `D`, representing a diamond, or `R`, representing a ruby. Find two cut positions that divide the circular necklace into two continuous parts such that both parts contain exactly the same number of diamonds and the same number of rubies. Return the two cut positions as `[start, end]`. The first part contains the characters encountered from `start` to `end` in clockwise order, and the remaining characters form the second part. If no valid split exists, return an empty array. The solution should efficiently handle a large necklace and avoid unnecessary duplication of the circular string.
Two Pointers
You are given two sparse time series, A and B. Each time series consists of events represented as (timestamp, value). The events in each series are sorted by timestamp in strictly increasing order. Each event means that starting from its timestamp, the corresponding series changes to the given value and keeps that value until the next event. Before the first event of a series, its value is assumed to be 0. Merge the two time series into one chronological sequence where each output event represents the sum of the current values of A and B. The output must be compressed: only record a timestamp when the combined value actually changes. If both sequences contain an event at the same timestamp, both updates must be applied atomically before calculating the combined value. The merged result must continue until all events from both sequences have been processed, including the case where one sequence ends earlier than the other. The final events must correctly preserve the last known value of the exhausted sequence.
Hash Table
Given an integer array nums and an integer target, find two distinct elements in the array whose values add up to target. Return the indices of the two elements whose sum equals target. You may assume that each input contains exactly one valid solution, and the same element cannot be used twice. The goal is to solve the problem using a single pass through the array with efficient lookup rather than checking every possible pair.
Greedy
Given a string s containing lowercase English letters, rearrange its characters so that no two identical characters are adjacent. Return any valid rearrangement of the string if one exists. If no valid rearrangement is possible, return an empty string. A valid rearrangement must use every character from the original string exactly once. A valid arrangement exists only when the frequency of the most common character does not exceed (n + 1) / 2, where n is the length of the string. This condition provides an early mathematical check for impossible inputs.
Design
Design and implement a user browsing history system for an e-commerce website. The system records the products that users have recently viewed and maintains their browsing history in order from most recently viewed to least recently viewed. The system should support the following operations: A user can view a product. If the product is already in the user's browsing history, it should be moved to the most recently viewed position. A user can retrieve their recent browsing history. Each user's browsing history has a fixed capacity. When the capacity is exceeded, the least recently viewed product should be removed. The system must support multiple users, and each user's browsing history must remain independent from other users. The core data structure should provide O(1) average-time lookup and O(1) update of browsing order.
Object-Oriented Design
Design a pizza ordering system that allows customers to create pizzas, add pizzas to an order, apply coupons, and calculate the final price. The system should represent individual pizzas with their names, base prices, and ingredients. An order should maintain the pizzas selected by the customer and calculate the subtotal and final total. The system should also support different types of coupons. Different coupon types may apply discounts according to different business rules, such as percentage discounts, fixed-amount discounts, buy-one-get-one offers, free-item offers, or minimum-spend discounts. The design should be extensible so that adding a new coupon type does not require modifying the core Order logic. The final order price must never be negative.
Data Structures and Algorithms
Design a log stream processor for a messaging application. Each incoming log event represents a message sent from one user to another and contains four fields: timestamp, sender_username, receiver_username, and message_text. Implement a RegisterEvent(timestamp, sender_username, receiver_username, message_text) method to register a message event and a GetMostActiveUser() method to return the user with the highest number of active conversations. A conversation is defined as a unique pair of users who have exchanged messages. Regardless of how many messages are sent between the same two users, the pair counts as only one conversation for each user. A conversation is counted for both participants, even if only one participant sends a message. For example, if Alice sends 100 messages to Bob, they still have only one conversation. If Alice also exchanges messages with Charlie and David, Alice has three unique conversation partners. The system should process incoming events incrementally and maintain the most active user efficiently, without scanning every user whenever GetMostActiveUser() is called.
Data Structures and Algorithms
Given a binary tree in which each node contains either 0 or 1, determine the total number of islands in the tree. An island consists of one or more nodes with value 1 that are connected through direct parent-child relationships. Two nodes with value 1 belong to the same island if there is a path between them consisting entirely of nodes with value 1. A node with value 0 separates islands. If a node with value 1 has a parent whose value is 0, or if the node is the root, it starts a new island. The tree is acyclic, and connectivity is defined only through parent-child relationships. The solution should count each island exactly once and should avoid unnecessary auxiliary data structures when possible.
Data Structures and Algorithms
Given a set of currency exchange rates, design a system that converts an amount from a source currency to a target currency through one or more intermediate currencies. Each exchange rate represents a directed conversion edge. For example, if 1 USD can be exchanged for 0.92 EUR, the graph contains an edge from USD to EUR with an exchange rate of 0.92. The system should support finding a valid conversion path between two currencies. During the interview, the interviewer may introduce additional requirements, such as minimizing the number of exchanges or maximizing the final converted amount. Different optimization objectives require different algorithms. Finding any valid path does not guarantee the minimum number of exchanges or the maximum converted amount. The implementation should clearly distinguish between these objectives and handle unreachable currencies appropriately.