# Interviews — User Guide

## 1. Quick Start

**Interviews** is a comprehensive collection of Java solutions for coding interview preparation. It covers LeetCode problems (organized by algorithm category), company-specific interview questions from top tech firms, Cracking the Coding Interview (CTCI) chapter exercises, and UVA Online Judge problems.

**Key features:**

- 500+ Java solutions spanning algorithms, data structures, and problem-solving patterns
- LeetCode problems organized by 21 algorithm categories (arrays, dynamic programming, trees, graphs, and more)
- Company-tagged questions for 15 major tech companies including Google, Facebook, Amazon, and Microsoft
- CTCI chapter exercises covering 7 core topic areas
- 47 UVA Online Judge competitive programming solutions
- Every solution file includes the problem statement as comments
- Clean, readable Java implementations with inline explanations

**Prerequisites:** Git and Java JDK 8 or later.

```bash
git clone https://github.com/kdn251/interviews.git
cd interviews
```

Open any solution file to study the problem and its implementation:

```bash
cat leetcode/array/BestTimeToBuyAndSellStock.java
```

```text
// Say you have an array for which the ith element is the price of a given stock on day i.
// If you were only permitted to complete at most one transaction ...
public class BestTimeToBuyAndSellStock {
    public int maxProfit(int[] prices) {
        //Kadane's algorithm
        ...
    }
}
```

> [!TIP]
> Start with `leetcode/array/` — array problems are the most common interview topic and the solutions here cover 29 distinct problems ranging from easy to hard.

**What to try next:** Browse company-specific problems in `company/google/` or `company/facebook/`, or study algorithm patterns in `leetcode/dynamic-programming/`.

## 2. Installation

### System Requirements

| Requirement | Minimum | Recommended |
|---|---|---|
| Java JDK | 8+ | 11+ |
| Git | Any modern version | Latest |
| Disk space | ~10 MB | ~10 MB |
| IDE (optional) | Any text editor | IntelliJ IDEA or VS Code with Java extension |

### Getting the Repository

=== "HTTPS"
    ```bash
    git clone https://github.com/kdn251/interviews.git
    ```

=== "SSH"
    ```bash
    git clone git@github.com:kdn251/interviews.git
    ```

=== "GitHub CLI"
    ```bash
    gh repo clone kdn251/interviews
    ```

### Verifying Your Setup

Compile any solution to confirm Java is working:

```bash
cd interviews/leetcode/array
javac BestTimeToBuyAndSellStock.java
```

```text
(no output on success)
```

> [!IMPORTANT]
> Most solution files are standalone classes without a `main` method — they are designed as algorithm implementations, not runnable programs. To test them, write a small driver class or use an IDE's built-in test runner. The UVA solutions are the exception: they include `main` methods with `Scanner`-based I/O for online judge submission.

### IDE Setup (Optional)

The repository includes IntelliJ IDEA project files (`interviews.iml`, `LeetCode.iml`, `CrackingTheCodingInterview.iml`, `Company.iml`). To open in IntelliJ:

1. Open IntelliJ IDEA
2. Select **File > Open**
3. Navigate to the cloned `interviews/` directory
4. Click **OK** — IntelliJ will detect the `.iml` files automatically

For VS Code, install the **Extension Pack for Java** and open the folder directly.

> [!NOTE]
> The `.iml` project files define IntelliJ module boundaries for the three main sections (LeetCode, Company, CTCI). They are not required for compilation — any Java-capable editor works.

## 3. Core Usage

### Understanding the Repository Structure

Solutions are organized into four top-level collections:

| Collection | Path | Problems | Focus |
|---|---|---|---|
| **LeetCode** | `leetcode/` | ~179 | Algorithm categories (array, DP, tree, etc.) |
| **Company** | `company/` | ~249 | Questions tagged to specific employers |
| **CTCI** | `cracking-the-coding-interview/` | ~39 | Book chapter exercises |
| **UVA** | `uva/` | 47 | Competitive programming problems |

### Browsing by Algorithm Category (LeetCode)

LeetCode solutions are grouped into 21 algorithm categories. Each file is named after the problem (e.g., `TwoSum.java`, `MergeIntervals.java`) and contains:

1. The full problem statement as comments at the top
2. A clean Java solution class
3. Inline comments explaining the approach

| Category | Files | Key Problems |
|---|---|---|
| `array` | 29 | Best Time to Buy/Sell Stock, Merge Intervals, Subsets, Rotate Image, Trapping Rain Water |
| `hash-table` | 24 | Two Sum, Group Anagrams, Valid Sudoku, Minimum Window Substring |
| `string` | 22 | Longest Palindromic Substring, Decode Ways, Valid Parentheses, Multiply Strings |
| `dynamic-programming` | 20 | Coin Change, House Robber, Word Break, Edit Distance, Regular Expression Matching |
| `two-pointers` | 10 | 3Sum, Move Zeros, Sort Colors, Remove Duplicates |
| `tree` | 8 | Binary Tree Maximum Path Sum, Validate BST, Lowest Common Ancestor |
| `bit-manipulation` | 8 | Hamming Distance, Power of Two, UTF-8 Validation, Counting Bits |
| `depth-first-search` | 7 | Number of Islands, Convert Sorted Array to BST, Balanced Binary Tree |
| `breadth-first-search` | 7 | Binary Tree Level Order Traversal, Clone Graph, Walls and Gates |
| `stack` | 7 | Min Stack, Decode String, Trapping Rain Water, Flatten Nested List Iterator |
| `linked-list` | 7 | Add Two Numbers, Merge K Sorted Lists, Reverse Linked List, Palindrome Linked List |
| `math` | 7 | Add Digits, Palindrome Number, Poor Pigs, Power of Two |
| `backtracking` | 5 | Generate Parentheses, Permutations, Letter Combinations of a Phone Number |
| `binary-search` | 5 | Closest BST Value, First Bad Version, Sqrt(x), Power of X to the N |
| `trie` | 3 | Implement Trie, Add and Search Word, Word Squares |
| `design` | 3 | Min Stack, Insert Delete GetRandom O(1), ZigZag Iterator |
| `divide-and-conquer` | 2 | Kth Largest Element, Expression Add Operators |
| `sort` | 2 | Meeting Rooms, Meeting Rooms II |
| `greedy` | 1 | Best Time to Buy and Sell Stock II |
| `queue` | 1 | Moving Average from Data Stream |
| `brainteaser` | 1 | Bulb Switcher |

> [!TIP]
> Many problems appear in multiple categories because they can be solved with different techniques. For example, `CountingBits.java` appears in both `bit-manipulation/` and `dynamic-programming/` — comparing both teaches you when to pick one pattern over another.

### Browsing by Company

The `company/` directory groups problems by the tech company known to ask them in interviews:

| Company | Files | Notable Problems |
|---|---|---|
| `facebook` | 65 | Expression Add Operators, Remove Invalid Parentheses, Word Search, Paint House II |
| `google` | 60 | Android Unlock Patterns, Bomb Enemy, Sentence Screen Fitting, Word Squares |
| `amazon` | 27 | Trapping Rain Water, Number of Islands, K-th Largest Element, Encode/Decode TinyURL |
| `uber` | 27 | Clone Graph, Decode Ways, Spiral Matrix, Palindrome Permutation |
| `linkedin` | 21 | Maximum Product Subarray, Merge K Sorted Lists, Sparse Matrix Multiplication |
| `twitter` | 12 | Multiply Strings, One Edit Distance, Regular Expression Matching |
| `airbnb` | 9 | Add Two Numbers, Merge K Sorted Lists, Regular Expression Matching |
| `microsoft` | 9 | Longest Increasing Subsequence, Spiral Matrix, Permutations |
| `bloomberg` | 6 | Min Stack, Unique Paths, Reverse Words in a String |
| `snapchat` | 3 | Min Stack, Valid Sudoku, Reverse Words in a String |
| `adobe` | 2 | Add Digits, Majority Element |
| `apple` | 2 | Reverse Words in a String, Valid Sudoku |
| `palantir` | 2 | Contains Duplicate, Contains Duplicates II |
| `yahoo` | 2 | Contains Duplicate, Linked List Cycle |
| `yelp` | 2 | Insert Delete GetRandom O(1), Reverse Words in a String |

> [!NOTE]
> The same problem often appears under multiple companies. For instance, `TwoSum.java` exists in `company/facebook/`, `company/amazon/`, `company/uber/`, `company/linkedin/`, and `company/airbnb/`. Each copy is the same implementation — the duplication reflects that multiple companies ask the same question.

### Browsing by CTCI Chapter

The `cracking-the-coding-interview/` directory follows the book's chapter structure:

| Chapter | Path | Files |
|---|---|---|
| Ch. 1: Arrays & Strings | `chapter-one-arrays-and-strings/` | 6 |
| Ch. 2: Linked Lists | `chapter-two-linked-lists/` | 5 |
| Ch. 3: Stacks & Queues | `chapter-three-stacks-and-queues/` | 8 |
| Ch. 4: Trees & Graphs | `chapter-four-trees-and-graphs/` | 7 |
| Ch. 5: Bit Manipulation | `chapter-five-bit-manipulation/` | 4 |
| Ch. 7: Math & Probability | `chapter-seven-mathematics-and-probability/` | 2 |
| Ch. 9: Recursion & DP | `chapter-nine-recursion-and-dynamic-programming/` | 7 |

### Browsing UVA Online Judge Solutions

The `uva/` directory contains 47 solutions for competitive programming problems from the UVA Online Judge. Unlike the LeetCode and company solutions, these include `main` methods with `Scanner`-based standard I/O, ready for direct submission.

```java
// Example structure: uva/AddingReversedNumbers.java
import java.math.BigInteger;
import java.util.Scanner;

public class AddingReversedNumbers {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int numberOfTestCases = input.nextInt();
        // ...processes input and prints reversed sum
    }
}
```

> [!WARNING]
> UVA solutions use `java.util.Scanner` for console input. When running them locally, you must provide input via stdin (pipe a file or type interactively). They will hang if launched without input.

## 4. Common Tasks

### Study a Specific Algorithm Pattern

**Goal:** Master a single algorithm technique (e.g., dynamic programming).

1. Navigate to the category folder:
   ```bash
   ls leetcode/dynamic-programming/
   ```
2. Start with simpler problems: `ClimbingStairs.java`, `HouseRobber.java`, `CoinChange.java`
3. Read the problem statement (top comments) before looking at the solution
4. Study the solution's approach — note the recurrence relation and base cases
5. Progress to harder problems: `EditDistance.java`, `RegularExpressionMatching.java`

### Prepare for a Company Interview

**Goal:** Review the most commonly asked questions for a specific company.

1. List problems for your target company:
   ```bash
   ls company/facebook/
   ```
   ```text
   3Sum.java                              MergeKSortedLists.java
   AddAndSearchWordDataStructureDesign.java  MergeSortedArray.java
   AddBinary.java                         MinStack.java
   ...65 files total
   ```
2. Cross-reference with the LeetCode category folders to understand which algorithm each problem tests
3. Solve the problems independently, then compare your solution with the repository's approach
4. Focus on the companies with the most problems (Facebook: 65, Google: 60, Amazon: 27) for the broadest coverage

### Work Through CTCI Systematically

**Goal:** Follow the Cracking the Coding Interview book chapter by chapter.

1. Open the book to the relevant chapter
2. Navigate to the matching directory:
   ```bash
   ls cracking-the-coding-interview/chapter-one-arrays-and-strings/
   ```
   ```text
   DeleteDups.java    IsUniqueChars.java  Permutation.java
   IsRotation.java    NthToLast.java      ReplaceSpaces.java
   ```
3. Attempt each problem on paper or in your IDE before reading the solution
4. Compare your approach with the repository's implementation
5. Note the techniques used — for example, `IsUniqueChars.java` uses an `int` as a 26-bit boolean array via bit manipulation

### Compare Multiple Approaches to the Same Problem

**Goal:** See how the same problem is solved differently across categories.

Some problems appear in multiple LeetCode category folders. To find all instances of a problem:

```bash
find . -name "TwoSum.java"
```

```text
./company/airbnb/TwoSum.java
./company/amazon/TwoSum.java
./company/facebook/TwoSum.java
./company/linkedin/TwoSum.java
./company/uber/TwoSum.java
./leetcode/hash-table/TwoSum.java
```

> [!TIP]
> When a problem appears in both a LeetCode category folder and a company folder, the implementations are typically identical. The LeetCode category tells you the **technique** (hash table), while the company tag tells you **where it is asked** (Facebook, Amazon, etc.).

### Compile and Test a Solution

**Goal:** Run a solution locally to verify it or experiment with modifications.

Most solutions lack a `main` method. Create a simple test driver:

```java
// TestDriver.java (create in same directory as the solution)
public class TestDriver {
    public static void main(String[] args) {
        BestTimeToBuyAndSellStock solution = new BestTimeToBuyAndSellStock();
        int[] prices = {7, 1, 5, 3, 6, 4};
        System.out.println(solution.maxProfit(prices)); // Expected: 5
    }
}
```

```bash
javac BestTimeToBuyAndSellStock.java TestDriver.java
java TestDriver
```

```text
5
```

### Study Data Structure Implementations

**Goal:** Learn how data structures are implemented from scratch.

Several solutions implement custom data structures:

| Data Structure | File | Key Insight |
|---|---|---|
| Min Stack | `leetcode/design/MinStack.java` | Linked list node stores both value and current minimum |
| Trie (Prefix Tree) | `leetcode/trie/ImplementTrie.java` | Array of 26 children per node |
| Randomized Set | `leetcode/design/InsertDeleteGetRandomO1.java` | HashMap + ArrayList for O(1) insert/delete/random |
| Queue via Stacks | `cracking-the-coding-interview/chapter-three-stacks-and-queues/QueueUsingTwoStacks.java` | Two-stack amortized O(1) dequeue |
| Set of Stacks | `cracking-the-coding-interview/chapter-three-stacks-and-queues/SetOfStacks.java` | Auto-splitting when capacity is reached |
| Zigzag Iterator | `leetcode/design/ZigZagIterator.java` | Iterator swapping for alternating traversal |

### Identify the Most-Asked Problems Across Companies

**Goal:** Find high-frequency problems that appear at many companies.

These problems appear in 4 or more company folders:

| Problem | Companies |
|---|---|
| Merge K Sorted Lists | Facebook, Google, Amazon, Uber, LinkedIn, Twitter, Airbnb |
| Insert Delete GetRandom O(1) | Facebook, Google, Amazon, Uber, Twitter, LinkedIn, Yelp |
| Valid Parentheses | Facebook, Google, Amazon, Twitter, Airbnb |
| Regular Expression Matching | Facebook, Google, Uber, Twitter, Airbnb |
| Min Stack | Facebook, Google, Amazon, Bloomberg, Uber, Snapchat |
| Two Sum | Facebook, Amazon, Uber, LinkedIn, Airbnb |
| Lowest Common Ancestor of a Binary Tree | Facebook, Google, Amazon, LinkedIn, Twitter |
| Reverse Linked List | Facebook, Amazon, Uber, Twitter |
| Number of Islands | Facebook, Google, Amazon |
| Merge Intervals | Facebook, Google, LinkedIn, Twitter |

## 5. Troubleshooting

### Error: `cannot find symbol`

**Cause:** Solution files reference standard library classes (`HashMap`, `ArrayList`, `LinkedList`) without explicit imports. The files are written as algorithm exercises, not complete compilation units.

**Solution:**
Add the necessary imports at the top of the file:

```java
import java.util.*;
```

**Prevention:** When creating test drivers, always include `import java.util.*;` at the top.

### Error: `class name doesn't match file name`

**Cause:** A few files have class names that differ from the filename. For example, `cracking-the-coding-interview/chapter-one-arrays-and-strings/DeleteDups.java` contains `class RemoveDups` instead of `class DeleteDups`.

**Solution:**
Either rename the class to match the file, or rename the file to match the class.

> [!WARNING]
> The file `company/google/RegularExpressionMatching.javaa` has a double-`a` extension (`.javaa` instead of `.java`). Rename it to compile: `mv RegularExpressionMatching.javaa RegularExpressionMatching.java`.

### Error: `cannot access Scanner` (UVA solutions)

**Cause:** UVA solutions use `java.util.Scanner` for stdin input. Running them without providing input causes the program to hang waiting for console input.

**Solution:**
Provide input via a file or pipe:

```bash
echo -e "3\n24 1\n4358 754\n305 794" | java AddingReversedNumbers
```

```text
34
1998
1
```

### Files won't compile due to missing type definitions

**Cause:** Some solutions reference helper types like `LinkedListNode`, `TreeNode`, or `ListNode` that are not defined in the repository. These are standard LeetCode platform-provided types.

**Solution:**
Define the missing class locally:

```java
// For linked list problems
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

// For tree problems
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) { val = x; }
}
```

**Prevention:** Keep a `Common.java` file with these definitions and compile it alongside any solution that needs them.

### Duplicate files across folders — which one to study?

**Cause:** The same problem (e.g., `TwoSum.java`) exists in multiple company folders and in a LeetCode category folder. The implementations are typically identical.

**Solution:**
Study the LeetCode category version — the folder name tells you the algorithm technique. The company folder copies exist to map problems to interview contexts.

> [!CAUTION]
> Do not assume every copy is identical. A small number of problems have minor implementation differences between the LeetCode and company versions. If you find a discrepancy, the LeetCode category version is generally the more polished implementation.

## 6. FAQ

**Q: What Java version do I need?**

Java 8 or later. The solutions use standard library collections (`HashMap`, `ArrayList`, `Arrays`), lambda-free iteration patterns, and no module system features. Any JDK from 8 onward compiles everything.

**Q: Are these solutions optimal?**

The solutions demonstrate clean, correct approaches but are not always the most space- or time-efficient possible. They prioritize readability and teaching the core algorithm pattern. For example, `FindAllNumbersDisappearedInAnArray.java` uses a HashMap where an in-place marking approach would use O(1) extra space.

**Q: Why are there duplicate files across company folders?**

The repository mirrors how interview prep works in practice — you study by target company. If Facebook, Google, and Amazon all ask "Merge K Sorted Lists," the file appears in all three company folders. This makes it easy to get a complete list of problems for any single company without cross-referencing.

**Q: Which section should I start with?**

For general interview prep, start with `leetcode/array/` and `leetcode/string/` — these are the most common categories. For targeted company prep, go directly to `company/{your_target}/`. For a structured curriculum, follow the CTCI chapters in order.

**Q: Can I submit the UVA solutions directly to the online judge?**

Yes. The UVA solutions include `main` methods with `Scanner`-based I/O matching the judge's expected format. Copy the file contents into the submission form. LeetCode and company solutions need the platform-specific `Solution` class wrapper that LeetCode provides.

**Q: Is there a build system (Maven, Gradle)?**

No. The repository has no build system, no `pom.xml`, no `build.gradle`. Each `.java` file is a standalone compilation unit. Compile individual files with `javac` or open the project in an IDE.

**Q: How do I contribute new solutions?**

Place your solution in the appropriate category folder, name the file after the problem (PascalCase), include the problem statement as comments at the top, and submit a pull request. See the Admin Guide for the full repository structure and coding conventions.

**Q: Why are some CTCI chapters missing (6, 8, 10+)?**

The repository covers chapters 1-5, 7, and 9. Chapters 6, 8, 10, and later are not yet implemented. GitHub issue [#211](https://github.com/kdn251/interviews/issues/211) discusses renaming and expanding chapter coverage. Issue [#144](https://github.com/kdn251/interviews/issues/144) requests more Adobe problems.

**Q: Are there any known content issues?**

GitHub issue [#200](https://github.com/kdn251/interviews/issues/200) reports a misleading example in the Greedy Algorithms section. Issue [#261](https://github.com/kdn251/interviews/issues/261) notes a duplication in the Queue data structure section. Check the issue tracker for current status.

---

_Generated May 2026 from kdn251/interviews at 03fdcb2. AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it. Unofficial; not affiliated with or reviewed by the project._
