0% found this document useful (0 votes)
46 views12 pages

Dsa Problems 2

This document is a comprehensive interview preparation guide focusing on Data Structures and Algorithms (DSA) and Database Queries (SQL) for software engineering roles. It covers key data structures, algorithms, common problems, and advanced topics, along with practical interview tips and resources. The goal is to equip candidates with the necessary skills and knowledge to excel in technical interviews at startups and mid-sized companies.

Uploaded by

Shahid Ameen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views12 pages

Dsa Problems 2

This document is a comprehensive interview preparation guide focusing on Data Structures and Algorithms (DSA) and Database Queries (SQL) for software engineering roles. It covers key data structures, algorithms, common problems, and advanced topics, along with practical interview tips and resources. The goal is to equip candidates with the necessary skills and knowledge to excel in technical interviews at startups and mid-sized companies.

Uploaded by

Shahid Ameen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Comprehensive Interview Preparation Guide for DSA and

Database Queries

July 15, 2025

Contents
1 Introduction 3

2 Data Structures and Algorithms (DSA) 3


2.1 Key Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.1.1 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.1.2 Linked Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.1.3 Stacks and Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.1.4 Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.1.5 Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.1.6 Hash Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.1.7 Heaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2 Key Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2.1 Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2.2 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2.3 Recursion and Backtracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2.4 Dynamic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2.5 Greedy Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2.6 Graph Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 Common DSA Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3.1 Problem 1: Reverse a Linked List . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3.2 Problem 2: Two Sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3.3 Problem 3: Merge Intervals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3.4 Problem 4: Longest Substring Without Repeating Characters . . . . . . . . . 6
2.3.5 Problem 5: Valid Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3.6 Problem 6: Top K Frequent Elements . . . . . . . . . . . . . . . . . . . . . . . . 7

3 Database Queries (SQL) 7


3.1 SQL Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Query Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.3 Common SQL Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.3.1 Problem 1: Highest Salary by Department . . . . . . . . . . . . . . . . . . . . . 8
3.3.2 Problem 2: Find Duplicate Emails . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3.3 Problem 3: Second Highest Salary . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3.4 Problem 4: Rank Scores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.3.5 Problem 5: Employees Earning More Than Managers . . . . . . . . . . . . . . 9
3.3.6 Problem 6: Customer Who Never Orders . . . . . . . . . . . . . . . . . . . . . 9

4 Advanced DSA Topics 9


4.1 Bit Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.2 Sliding Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.3 Two Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

1
CONTENTS

4.4 Trie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

5 Advanced SQL Topics 10


5.1 Database Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
5.2 Complex Joins and Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.3 Performance Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

6 Interview Tips 11

7 Practice Resources 12

8 Conclusion 12

2
2 DATA STRUCTURES AND ALGORITHMS (DSA)

1 Introduction
This guide is tailored for candidates preparing for technical interviews at startups and mid-
sized companies for entry to mid-level software engineering roles. It provides an in-depth ex-
ploration of Data Structures and Algorithms (DSA) and Database Queries (SQL), covering the-
oretical concepts, practical problem-solving, and common interview questions. The goal is to
equip you with the knowledge and skills to confidently tackle interviews, with a focus on topics
prevalent in dynamic, fast-paced environments.

2 Data Structures and Algorithms (DSA)


DSA is a cornerstone of technical interviews, testing your ability to solve problems efficiently.
This section covers key data structures, algorithms, and practical problems.

2.1 Key Data Structures


Startups and mid-sized companies often focus on practical applications of data structures. Be-
low are the most commonly tested ones:

2.1.1 Arrays

Arrays store elements in contiguous memory, enabling O(1) access. They’re used for problems
involving indexing, sorting, and searching.
• Operations: Access O(1), Search O(n), Insert/Delete O(n).
• Interview Focus: Two-pointer techniques, sliding windows, and subarray problems.

2.1.2 Linked Lists

Linked lists consist of nodes with data and pointers. Variants include singly, doubly, and circu-
lar lists.
• Operations: Access O(n), Insert/Delete O(1) at head/tail.
• Interview Focus: Reversal, cycle detection, merging lists.

2.1.3 Stacks and Queues

Stacks (LIFO) and queues (FIFO) are used for problems requiring ordered processing.
• Stack Operations: Push, Pop, Peek (O(1)).
• Queue Operations: Enqueue, Dequeue (O(1)).
• Interview Focus: Parentheses validation, monotonic stacks, sliding window maximum.

2.1.4 Trees

Trees are hierarchical structures, with Binary Search Trees (BSTs) and balanced trees (AVL,
Red-Black) being common.
• Operations: Search/Insert/Delete O(log n) for balanced trees, O(n) for unbalanced.
• Interview Focus: Traversal (preorder, inorder, postorder), lowest common ancestor, tree
height.

3
2 DATA STRUCTURES AND ALGORITHMS (DSA)

2.1.5 Graphs

Graphs consist of nodes and edges, represented via adjacency lists or matrices.
• Operations: Traversal (DFS, BFS) O(V + E), Shortest Path (Dijkstra) O((V + E) log V).
• Interview Focus: Connected components, shortest paths, cycle detection.

2.1.6 Hash Tables

Hash tables provide average O(1) operations using key-value pairs, with collisions handled via
chaining or open addressing.
• Operations: Insert, Search, Delete O(1) average, O(n) worst case.
• Interview Focus: Two-sum, grouping anagrams, detecting duplicates.

2.1.7 Heaps

Heaps (min/max) are used for priority-based problems.


• Operations: Insert, Extract Min/Max O(log n).
• Interview Focus: Top K elements, median in a stream.

2.2 Key Algorithms


Understanding algorithmic paradigms is critical for interviews.

2.2.1 Sorting

• Bubble/Selection/Insertion Sort: O(n²), simple but inefficient.


• Merge/Quick/Heap Sort: O(n log n), commonly used.
• Interview Focus: Quick Sort implementation, handling edge cases.

2.2.2 Searching

• Linear Search: O(n), used for unsorted data.


• Binary Search: O(log n), requires sorted data.
• Interview Focus: Variants like finding the first/last occurrence.

2.2.3 Recursion and Backtracking

Recursion breaks problems into smaller subproblems, while backtracking explores all possibil-
ities.
• Examples: N-Queens, Subsets, Permutations.
• Interview Focus: Writing clean recursive code, avoiding stack overflow.

2.2.4 Dynamic Programming

DP optimizes recursive solutions using memoization or tabulation.


• Examples: Fibonacci, Knapsack, Longest Common Subsequence.
• Interview Focus: Identifying overlapping subproblems, state transitions.

4
2 DATA STRUCTURES AND ALGORITHMS (DSA)

2.2.5 Greedy Algorithms

Greedy algorithms make locally optimal choices.


• Examples: Activity Selection, Fractional Knapsack.
• Interview Focus: Proving optimality, edge cases.

2.2.6 Graph Algorithms

• DFS/BFS: O(V + E), for traversal and pathfinding.


• Dijkstra/Bellman-Ford: For shortest paths.
• Interview Focus: Cycle detection, topological sort.

2.3 Common DSA Problems


Below are detailed solutions to problems frequently asked in startups and mid-sized companies.

2.3.1 Problem 1: Reverse a Linked List

Problem: Reverse a singly linked list.


Solution:
1 class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6 def reverseList(head):
7 prev = None
8 current = head
9 while current:
10 next_node = current.next
11 current.next = prev
12 prev = current
13 current = next_node
14 return prev

Explanation: Iteratively reverse pointers.


Time Complexity: O(n), Space Complexity: O(1).
Edge Cases: Empty list, single node.

2.3.2 Problem 2: Two Sum

Problem: Find indices of two numbers in an array that add up to a target.


Solution:
1 def twoSum(nums, target):
2 seen = {}
3 for i, num in enumerate(nums):
4 complement = target - num
5 if complement in seen:
6 return [seen[complement], i]
7 seen[num] = i
8 return []

Explanation: Use a hash map to store numbers and indices.


Time Complexity: O(n), Space Complexity: O(n).
Edge Cases: No solution, duplicates.

5
2 DATA STRUCTURES AND ALGORITHMS (DSA)

2.3.3 Problem 3: Merge Intervals

Problem: Merge overlapping intervals in a list.


Solution:
1 def merge(intervals):
2 intervals.sort(key=lambda x: x[0])
3 merged = []
4 for interval in intervals:
5 if not merged or merged[-1][1] < interval[0]:
6 merged.append(interval)
7 else:
8 merged[-1][1] = max(merged[-1][1], interval[1])
9 return merged

Explanation: Sort by start time, merge overlapping intervals.


Time Complexity: O(n log n), Space Complexity: O(n).
Edge Cases: Empty list, non-overlapping intervals.

2.3.4 Problem 4: Longest Substring Without Repeating Characters

Problem: Find the length of the longest substring without repeating characters.
Solution:
1 def lengthOfLongestSubstring(s):
2 seen = {}
3 max_length = 0
4 start = 0
5 for end in range(len(s)):
6 if s[end] in seen and seen[s[end]] >= start:
7 start = seen[s[end]] + 1
8 else:
9 max_length = max(max_length, end - start + 1)
10 seen[s[end]] = end
11 return max_length

Explanation: Use a sliding window with a hash map to track character positions.
Time Complexity: O(n), Space Complexity: O(min(m, n)).
Edge Cases: Empty string, all unique characters.

2.3.5 Problem 5: Valid Parentheses

Problem: Check if a string of parentheses is valid.


Solution:
1 def isValid(s):
2 stack = []
3 brackets = {’)’: ’(’, ’}’: ’{’, ’]’: ’[’}
4 for char in s:
5 if char in brackets.values():
6 stack.append(char)
7 elif char in brackets:
8 if not stack or stack.pop() != brackets[char]:
9 return False
10 return len(stack) == 0

Explanation: Use a stack to match opening and closing brackets.


Time Complexity: O(n), Space Complexity: O(n).
Edge Cases: Empty string, unbalanced brackets.

6
3 DATABASE QUERIES (SQL)

2.3.6 Problem 6: Top K Frequent Elements

Problem: Find the k most frequent elements in an array.


Solution:
1 from collections import Counter
2 import heapq
3
4 def topKFrequent(nums, k):
5 count = Counter(nums)
6 return heapq.nlargest(k, count.keys(), key=count.get)

Explanation: Use a counter and heap to extract top k elements.


Time Complexity: O(n log n), Space Complexity: O(n).
Edge Cases: k equals array length, single element.

3 Database Queries (SQL)


SQL is critical for roles involving data manipulation and retrieval. This section covers SQL
theory, query types, and common problems.

3.1 SQL Fundamentals


• Database Structure: Tables (rows, columns), primary keys (unique identifiers), foreign
keys (relationships).
• Data Types: INT, VARCHAR, DATE, FLOAT, BOOLEAN.
• Constraints: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK.
• Normalization: 1NF (atomic values), 2NF (no partial dependency), 3NF (no transitive de-
pendency), BCNF.
• Indexes: B-Tree (range queries), Hash (equality queries). Trade-offs: Faster SELECT, slower
INSERT/UPDATE.

3.2 Query Types


• SELECT: Retrieve data. Syntax: SELECT column FROM table WHERE condition.
• JOIN: INNER (matching rows), LEFT (all left table rows), RIGHT, FULL.
• GROUP BY: Aggregate functions (COUNT, SUM, AVG, MAX, MIN).
• SUBQUERIES: Nested queries for filtering or calculations.
• WINDOW FUNCTIONS: ROW_NUMBER, RANK, DENSE_RANK, NTILE.
• DDL/DML: CREATE, ALTER, DROP (DDL); INSERT, UPDATE, DELETE (DML).
• Transactions: ACID properties (Atomicity, Consistency, Isolation, Durability).

3.3 Common SQL Problems


Below are detailed SQL problems with solutions.

7
3 DATABASE QUERIES (SQL)

3.3.1 Problem 1: Highest Salary by Department

Problem: Given employees (id, name, salary, dept_id) and departments (dept_id, dept_name),
find the highest-paid employee per department.
Solution:
1 SELECT d.dept_name, e.name, e.salary
2 FROM employees e
3 JOIN departments d ON e.dept_id = d.dept_id
4 WHERE (e.dept_id, e.salary) IN (
5 SELECT dept_id, MAX(salary)
6 FROM employees
7 GROUP BY dept_id
8 );

Explanation: Use a subquery to find max salary per department, then join with employee
details.
Alternative: Use a window function:
1 SELECT dept_name, name, salary
2 FROM (
3 SELECT d.dept_name, e.name, e.salary,
4 RANK() OVER (PARTITION BY e.dept_id ORDER BY e.salary DESC) AS rnk
5 FROM employees e
6 JOIN departments d ON e.dept_id = d.dept_id
7 ) t
8 WHERE rnk = 1;

3.3.2 Problem 2: Find Duplicate Emails

Problem: Given person (id, email), find all duplicate emails.


Solution:
1 SELECT email
2 FROM person
3 GROUP BY email
4 HAVING COUNT(*) > 1;

Explanation: Group by email and filter for counts greater than 1.


Alternative: Use a self-join:
1 SELECT DISTINCT p1.email
2 FROM person p1
3 JOIN person p2 ON p1.email = p2.email AND p1.id != p2.id;

3.3.3 Problem 3: Second Highest Salary

Problem: Find the second highest salary from employees (id, salary).
Solution:
1 SELECT MAX(salary) AS second_highest_salary
2 FROM employees
3 WHERE salary < (SELECT MAX(salary) FROM employees);

Explanation: Subquery finds max salary, outer query finds max below it.
Edge Cases: No second salary (return NULL), duplicate salaries.

8
4 ADVANCED DSA TOPICS

3.3.4 Problem 4: Rank Scores

Problem: Given scores (id, score), assign ranks with ties getting the same rank.
Solution:
1 SELECT score, DENSE_RANK() OVER (ORDER BY score DESC) AS rank
2 FROM scores;

Explanation: Use DENSE_RANK for consecutive ranks with ties.


Alternative: Use RANK for gaps in ranks.

3.3.5 Problem 5: Employees Earning More Than Managers

Problem: Given employees (id, name, salary, manager_id), find employees earning more than
their managers.
Solution:
1 SELECT e1.name AS employee
2 FROM employees e1
3 JOIN employees e2 ON e1.manager_id = e2.id
4 WHERE e1.salary > e2.salary;

Explanation: Self-join to compare employee and manager salaries.

3.3.6 Problem 6: Customer Who Never Orders

Problem: Given customers (id, name) and orders (id, customer_id), find customers who
never ordered.
Solution:
1 SELECT name
2 FROM customers
3 LEFT JOIN orders ON customers.id = orders.customer_id
4 WHERE orders.id IS NULL;

Explanation: LEFT JOIN keeps all customers, filter for NULL orders.

4 Advanced DSA Topics


Startups often test advanced concepts to gauge problem-solving depth.

4.1 Bit Manipulation


Used for low-level optimizations.
• Operations: AND, OR, XOR, shifts.
• Example Problem: Find the single number in an array where others appear twice.
• Solution:
1 def singleNumber(nums):
2 result = 0
3 for num in nums:
4 result ^= num
5 return result

9
5 ADVANCED SQL TOPICS

4.2 Sliding Window


For substring/subarray problems.
• Example: Maximum sum subarray of size k.
• Solution:
1 def maxSumSubarray(arr, k):
2 window_sum = sum(arr[:k])
3 max_sum = window_sum
4 for i in range(len(arr) - k):
5 window_sum = window_sum - arr[i] + arr[i + k]
6 max_sum = max(max_sum, window_sum)
7 return max_sum

4.3 Two Pointers


For problems requiring traversal from both ends.
• Example: Container with most water.
• Solution:
1 def maxArea(height):
2 left, right = 0, len(height) - 1
3 max_area = 0
4 while left < right:
5 area = min(height[left], height[right]) * (right - left)
6 max_area = max(max_area, area)
7 if height[left] < height[right]:
8 left += 1
9 else:
10 right -= 1
11 return max_area

4.4 Trie
For string-related problems like autocomplete.
• Example: Implement a trie with insert and search.
• Solution: (Omitted for brevity, focus on node structure and traversal).

5 Advanced SQL Topics


Mid-sized companies may test complex queries and database design.

5.1 Database Design


• Schema Design: Create tables with appropriate keys and constraints.
• Example: Design a schema for an e-commerce platform (products, orders, customers).
• Solution:
1 CREATE TABLE customers (
2 customer_id INT PRIMARY KEY,
3 name VARCHAR(100) NOT NULL,
4 email VARCHAR(100) UNIQUE
5 );
6

10
6 INTERVIEW TIPS

7 CREATE TABLE products (


8 product_id INT PRIMARY KEY,
9 name VARCHAR(100) NOT NULL,
10 price DECIMAL(10,2) NOT NULL
11 );
12
13 CREATE TABLE orders (
14 order_id INT PRIMARY KEY,
15 customer_id INT,
16 product_id INT,
17 order_date DATE,
18 FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
19 FOREIGN KEY (product_id) REFERENCES products(product_id)
20 );

5.2 Complex Joins and Subqueries


• Example: Find customers who ordered all products.
• Solution:
1 SELECT c.name
2 FROM customers c
3 WHERE NOT EXISTS (
4 SELECT p.product_id
5 FROM products p
6 WHERE NOT EXISTS (
7 SELECT 1
8 FROM orders o
9 WHERE o.customer_id = c.customer_id
10 AND o.product_id = p.product_id
11 )
12 );

5.3 Performance Optimization


• Indexes: Use for frequent WHERE/JOIN columns.
• Query Optimization: Avoid SELECT *, use EXPLAIN to analyze queries.
• Example: Index for frequent searches:
1 CREATE INDEX idx_customer_email ON customers(email);

6 Interview Tips
• Clarify Requirements: Ask about input size, edge cases, constraints.
• Explain Thought Process: Verbalize your approach before coding.
• Optimize Solutions: Discuss trade-offs (e.g., time vs. space).
• Test Thoroughly: Check edge cases (empty input, duplicates).
• Whiteboard Practice: Simulate coding without an IDE.
• SQL Best Practices: Write readable queries, avoid nested subqueries when possible.

11
8 CONCLUSION

7 Practice Resources
• DSA: LeetCode, HackerRank, Codeforces.
• SQL: SQLZoo, LeetCode Database, HackerRank SQL.
• Books: ”Cracking the Coding Interview” by Gayle Laakmann McDowell, ”Introduction to
Algorithms” by Cormen.

8 Conclusion
This guide covers the essential DSA and SQL topics for technical interviews at startups and
mid-sized companies. Practice the problems, understand the theory, and communicate your
solutions clearly. With consistent preparation, you’ll be well-equipped to crack your interview.
Good luck!

12

You might also like