Phase 2: Intermediate (66 problems)
Total: 66 problems
Problem 12: Number Guessing Game ⭐⭐
Concepts: While Loop, Random Numbers, User Interaction
What You'll Learn:
Using
RandomclassImplementing game logic with loops
Providing user feedback
Requirements:
Generate random number (1-100)
Let user guess
Give hints: "Too high" / "Too low"
Count attempts
Congratulate on correct guess
Bonus Challenges:
Add difficulty levels (range size)
Limit number of attempts
High score tracking
Play again option
Problem 13: Sum and Average Calculator ⭐⭐
Concepts: Arrays, Loops, Aggregation
What You'll Learn:
Using arrays to store multiple values
Iterating through arrays
Calculating aggregates
Requirements:
Ask how many numbers to enter
Store in array
Calculate and display:
Sum
Average
Maximum
Minimum
Bonus Challenges:
Find median value
Calculate standard deviation
Display as a bar chart (ASCII)
Problem 14: Prime Number Checker ⭐⭐
Concepts: Loops, Optimization, Boolean Logic
What You'll Learn:
Implementing efficient algorithms
Optimizing loop conditions
Understanding mathematical properties
Requirements:
Check if a number is prime
Only check divisors up to √n
Handle edge cases (1, 2, negative numbers)
Bonus Challenges:
Find all primes in a range
Implement Sieve of Eratosthenes
Count primes up to N
Problem 16: Fibonacci Series Generator ⭐⭐
Concepts: Loop Patterns, Sequence Logic
What You'll Learn:
Generating sequences
Using multiple variables to track state
Understanding Fibonacci properties
Requirements:
Generate first N Fibonacci numbers
Start with 0, 1
Display series: 0, 1, 1, 2, 3, 5, 8...
Bonus Challenges:
Find Nth Fibonacci number only
Use recursion with memoization
Find Fibonacci numbers up to a limit
Problem 19: Armstrong Number Checker ⭐⭐
Concepts: Loops, Power Function, Digit Processing
What You'll Learn:
Using Math.Pow()
Counting digits
Complex number properties
Requirements:
Check if number is Armstrong
Armstrong: Sum of cubes of digits equals number
Example: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
Bonus Challenges:
Find all Armstrong numbers in range
Generalize for n-digit numbers
Find next Armstrong number
Problem 20: Perfect Number Validator ⭐⭐
Concepts: Nested Loops, Divisor Logic
What You'll Learn:
Finding divisors efficiently
Understanding number theory
Optimizing with early termination
Requirements:
Check if number is perfect
Perfect: sum of proper divisors equals number
Example: 6 = 1 + 2 + 3
Bonus Challenges:
Find all perfect numbers up to N
Classify as abundant or deficient
Find all friendly pairs
Section 1.3: Pattern Printing
Focus: Nested loops, spacing logic, visual output
Problem 22: Pyramid Pattern ⭐⭐
Concepts: Loop Control, Spacing, Centering
What You'll Learn:
Calculating spaces for centering
Symmetric pattern building
Mathematical relationships in patterns
Requirements: Print centered pyramid:
Bonus Challenges:
Inverted pyramid
Diamond pattern
Number pyramid
Problem 23: Diamond Pattern ⭐⭐
Concepts: Complex Nesting, Symmetry
What You'll Learn:
Combining ascending and descending patterns
Managing multiple loop variables
Creating symmetric designs
Requirements: Print diamond:
Bonus Challenges:
Hollow diamond
Number diamond
Variable size diamond
Problem 24: Number Pyramid ⭐⭐
Concepts: Variable Patterns, Formatting
What You'll Learn:
Printing variable content
Maintaining alignment with varying widths
Number sequences in patterns
Requirements:
Bonus Challenges:
Reverse number pyramid
Floyd's triangle
Pascal's triangle
Problem 25: Floyd's Triangle ⭐⭐
Concepts: Sequence Generation, Display
What You'll Learn:
Maintaining state across loops
Generating sequences
Formatting numerical output
Requirements:
Bonus Challenges:
Floyd's triangle with custom starting number
Binary Floyd's triangle
Alphabetic Floyd's triangle
Section 1.4: Methods & Code Organization
Focus: Breaking code into reusable methods, parameters, return values
Problem 26: Palindrome Checker ⭐⭐
Concepts: Methods, String Manipulation
What You'll Learn:
Creating methods with return values
String reversal techniques
Case-insensitive comparison
Requirements: Create method bool IsPalindrome(string input):
Remove spaces and convert to lowercase
Check if string reads same backwards
Return true/false
Bonus Challenges:
Ignore punctuation
Check numeric palindromes
Find longest palindrome in text
Problem 28: String Analyzer ⭐⭐
Concepts: Multiple Methods, Analysis
What You'll Learn:
Breaking complex tasks into methods
Character analysis
Organizing related methods
Requirements: Create methods to analyze a string:
CountVowels(string s)CountConsonants(string s)CountDigits(string s)CountSpecialChars(string s)
Bonus Challenges:
Create a full report method
Find character frequency
Identify most common character
Problem 29: Simple Menu System ⭐⭐
Concepts: Methods, Switch, Loop Control
What You'll Learn:
Organizing code into menu-driven interface
Using methods for each operation
Controlling program flow with loops
Requirements: Create menu with options:
Add two numbers
Subtract
Multiply
Divide
Exit Each operation should be a separate method.
Bonus Challenges:
Add scientific calculator functions
Save calculation history
Support chained operations
Problem 30: Student Grades Summary ⭐⭐
Concepts: Arrays, Multiple Methods, Analysis
What You'll Learn:
Processing arrays with methods
Statistical calculations
Organizing data analysis code
Requirements: Create methods:
GetHighest(int[] marks)GetLowest(int[] marks)GetAverage(int[] marks)CountPassing(int[] marks, int passMark)AssignGrade(double average)
Bonus Challenges:
Calculate standard deviation
Rank students
Generate report card
Problem 31: GCD and LCM Calculator ⭐⭐
Concepts: Algorithm Implementation, Recursion
What You'll Learn:
Implementing Euclidean algorithm
Recursive vs iterative approaches
Mathematical relationships (GCD × LCM = a × b)
Requirements:
int GCD(int a, int b)using Euclidean algorithmint LCM(int a, int b)using GCDHandle edge cases (0, negative numbers)
Bonus Challenges:
GCD/LCM for multiple numbers
Implement extended Euclidean algorithm
Optimize for large numbers
Problem 32: Power Calculator (Custom) ⭐⭐
Concepts: Recursion Introduction, Base Cases
What You'll Learn:
Understanding recursion
Base case and recursive case
Comparing recursion with loops
Requirements: Implement double Power(int base, int exponent):
Handle positive exponents
Handle zero exponent
Handle negative exponents
Bonus Challenges:
Optimize with fast exponentiation (O(log n))
Compare recursive vs iterative performance
Handle very large exponents
Problem 33: Array Statistics Module ⭐⭐
Concepts: Parameters, Return Values, Multiple Calculations
What You'll Learn:
Passing arrays to methods
Returning multiple values (using out parameters or tuples)
Organizing statistical functions
Requirements: Create comprehensive stats module:
Mean, Median, Mode
Range, Variance, Standard Deviation
Quartiles
Bonus Challenges:
Implement using tuples for multiple returns
Add percentile calculation
Create histogram visualization
Problem 34: Text Formatter Tool ⭐⭐
Concepts: String Methods, Validation, Formatting
What You'll Learn:
String manipulation techniques
Text formatting standards
Input validation
Requirements: Create methods:
ToTitleCase(string s)- Capitalize Each WordToCamelCase(string s)- camelCaseToSnakeCase(string s)- snake_caseToKebabCase(string s)- kebab-case
Bonus Challenges:
Add PascalCase
Validate naming conventions
Convert between all formats
Problem 38: Bank Account Manager ⭐⭐
Concepts: Encapsulation, Properties, Validation
What You'll Learn:
Private fields with public properties
Data validation in setters
Business logic in methods
Requirements: Create BankAccount class:
Bonus Challenges:
Add transaction history (List of transactions)
Implement minimum balance requirement
Add interest calculation
Create multiple account types
Problem 39: Employee Management ⭐⭐
Concepts: Private Fields, Validation, Business Logic
Requirements: Create Employee class with validation:
Properties:
Name,Age,Salary,DepartmentAge must be 18-65
Salary must be > 0
Name cannot be empty
Methods:
GiveRaise(decimal percentage),DisplayInfo()
Bonus:
Add employee ID auto-generation
Track employment date
Calculate years of service
Implement performance rating system
Problem 41: Static Members & Counters ⭐⭐
Concepts: Static Fields, Static Methods, Static Constructors
What You'll Learn:
Difference between instance and static members
Using static for shared data
Static constructors
Requirements: Create Product class:
Bonus:
Add static method to find product by ID
Implement singleton pattern
Track most expensive product
Problem 42: Product Catalog System ⭐⭐
Concepts: Multiple Objects, Collections Integration
Requirements: Build a product catalog:
Create
Productclass (id, name, price, category)Store products in a List
Methods: Add, Remove, Search, Display
Calculate total inventory value
Bonus:
Group by category
Sort by price
Apply discount to category
Low stock alerts
Problem 43: Student Report Card ⭐⭐
Concepts: Class Design, Calculations, Formatting
Requirements: Create Student class:
Properties: Name, Roll Number, Subjects (Dictionary<string, int>)
Methods:
AddMarks(string subject, int marks)CalculateTotal()CalculatePercentage()GetGrade()GenerateReportCard()
Bonus:
Rank students by percentage
Subject-wise topper
Pass/Fail status
Graphical representation (ASCII art)
Section 2.2: Inheritance & Polymorphism (8 Problems)
Problem 45: Vehicle with Constructor Chain ⭐⭐
Concepts: base() keyword, Constructor Chaining
Requirements:
Observe constructor execution order.
Bonus: Create Motorcycle, Truck subclasses
Problem 48: Method Overriding ⭐⭐
Concepts: virtual, override, base keyword
Requirements:
Problem 49: Interface Implementation ⭐⭐
Concepts: Interfaces, Multiple Inheritance
Requirements:
Bonus: Add IDownloadable interface
Problem 50: Multiple Interface Demo ⭐⭐
Concepts: Polymorphic Behavior with Interfaces
Requirements: Create interfaces:
IMovable(Move(), Speed property)IAttackable(Attack(), Damage property)
Create classes that implement various combinations:
Player(IMovable, IAttackable)Enemy(IMovable, IAttackable)NPC(IMovable)
Demonstrate polymorphic collections.
Problem 54: Operator Overloading ⭐⭐
Concepts: Operator Overloading, Custom Operators
Requirements:
Bonus: Implement ToString override
Problem 55: Indexer Implementation ⭐⭐
Concepts: Custom [] Operator
Requirements:
Problem 63: Second Largest Element ⭐⭐
Problem 64: Remove Duplicates ⭐⭐
Problem 65: Rotate Array (Left/Right) ⭐⭐
Problem 67: Find Missing Number ⭐⭐
Problem 68: Move Zeros to End ⭐⭐
Problem 73: List of Objects (CRUD) ⭐⭐
Problem 74: HashSet Duplicate Removal ⭐⭐
Problem 75: HashSet Union/Intersection ⭐⭐
Problem 76: Dictionary Basics ⭐⭐
Problem 77: Character Frequency Counter ⭐⭐
Problem 81: Stack Implementation (Array) ⭐⭐
Requirements:
Problem 82: Queue Implementation (Array) ⭐⭐
Problem 84: Reverse String Using Stack ⭐⭐
Problem 91: Generic Value Swapper ⭐⭐
Concepts: Generic Methods, Type Parameters, ref Keyword, Type Inference
What You'll Learn:
Creating generic methods
Using type parameters (T, TKey, TValue)
Type inference (compiler figures out T)
Generic constraints basics
When generics are better than object
Requirements: Create a generic swap method that:
Works with any data type
Uses ref parameters to modify originals
Demonstrates type safety
Show type inference in action
Complete Implementation:
Why Generics?
Type Inference Example:
Test Cases:
Bonus Challenges:
⭐⭐ Create generic Min/Max methods
⭐⭐ Create generic array rotation method
⭐⭐⭐ Add constraint:
where T : IComparable<T>⭐⭐⭐ Create three-way swap (a→b, b→c, c→a)
Real-World Usage:
Collection libraries (List, Dictionary<K,V>)
LINQ methods (Where, Select<T,R>)
Utility methods
Framework code
Interview Tips: 💡 Always explain: "Generics provide type safety without boxing" 💡 Know the difference: Generic vs Object vs Overloading 💡 Understand type inference
Problem 93: Nullable Product Pricing ⭐⭐
Concepts: Nullable Types, Null-Coalescing Operators, Value Types, Nullable
What You'll Learn:
Nullable value types (int?, double?)
Null-coalescing operator (??)
Null-conditional operator (?.)
Null-coalescing assignment (??=)
HasValue and Value properties
Difference between reference and value type nullability
Requirements: Create a product pricing system that handles:
Optional discount (nullable decimal)
Optional tax rate (nullable decimal)
Use ?? operator for defaults
Use ?. for safe navigation
Demonstrate all nullable operators
Complete Implementation:
Visual Representation:
Nullable Operators Cheat Sheet:
Test Cases:
Bonus Challenges:
⭐⭐ Add nullable shipping cost
⭐⭐ Handle nullable quantity with default 1
⭐⭐⭐ Chain multiple nullable calculations
⭐⭐⭐ Implement custom nullable type wrapper
Real-World Usage:
Optional configuration values
Database fields that allow NULL
User input that may be missing
API responses with optional fields
Interview Tips: 💡 Know the difference: T? for value types, reference types nullable by default
💡 Explain: "?? provides default for null values"
💡 Mention C# 8.0 nullable reference types
Problem 96: Extension Method Playground ⭐⭐
Concepts: Extension Methods, this Keyword, Static Classes, Method Chaining
What You'll Learn:
Creating extension methods
Extending built-in types (string, int, IEnumerable)
Method chaining
LINQ-style extensions
Limitations of extension methods
Requirements: Create useful extension methods for:
String manipulation
Integer operations
Collection processing
Method chaining examples
Complete Implementation:
Extension Method Syntax Explained:
Method Chaining:
Extension Method Rules:
✅ Must be in static class
✅ Must be static method
✅ First parameter has
thiskeyword✅ Can extend any type (even sealed!)
❌ Cannot access private members
❌ Instance methods have priority over extensions
❌ Cannot override existing methods
Real-World Examples:
Test Cases:
Bonus Challenges:
⭐⭐ Create DateTime extensions (AddWeeks, IsWeekend)
⭐⭐ Create List extensions (AddRange with condition)
⭐⭐⭐ Create custom LINQ-style operators
⭐⭐⭐⭐ Build fluent API using extensions
Real-World Usage:
LINQ (Where, Select, OrderBy, etc.)
ASP.NET Core (AddMvc, UseRouting, etc.)
Entity Framework (Include, ThenInclude, etc.)
Custom utility libraries
Interview Tips: 💡 Mention: "LINQ is built entirely on extension methods" 💡 Explain: "First parameter with 'this' makes it an extension" 💡 Know: "Can extend sealed classes and interfaces" 💡 Important: "Cannot access private members"
✅ Section 4.1 Complete!
Generics & Constraints (6/6 Problems) ✅
Concepts Mastered:
✅ Generic methods and classes
✅ Type parameters (T, TKey, TValue)
✅ Type constraints (where clauses)
✅ Nullable types and operators
✅ Static classes and methods
✅ Partial classes
✅ Extension methods
🎯 Next Up: Section 4.2 - LINQ Mastery
THIS IS THE MOST IMPORTANT SECTION FOR JOBS!
LINQ appears in:
95% of C# job descriptions
Every real-world C# application
Most common interview questions
10 Problems covering:
Query syntax vs Method syntax
Filtering, Sorting, Projecting
Grouping, Joining, Aggregating
Performance optimization
Custom operators
Ready to master LINQ? 🚀
Problem 97: LINQ Filtering & Sorting ⭐⭐
Concepts: Where, OrderBy, OrderByDescending, ThenBy, Method Syntax vs Query Syntax
What You'll Learn:
Filtering with Where()
Single and multi-level sorting
Method syntax (fluent API)
Query syntax (SQL-like)
When to use each syntax
Chaining LINQ operations
Requirements: Work with a collection of products:
Filter by price range
Filter by category
Sort by price
Multi-level sorting (category, then price)
Show both method and query syntax
Complete Implementation:
Method Syntax vs Query Syntax Comparison:
Common LINQ Filtering Patterns:
Sorting Patterns:
Performance Tips:
Bonus Challenges:
⭐⭐ Add pagination (Skip, Take)
⭐⭐ Implement search across multiple fields
⭐⭐⭐ Create dynamic sorting based on user input
⭐⭐⭐ Optimize for very large collections
Real-World Usage:
E-commerce product filtering
Search results sorting
Admin dashboards
Report generation
Data grids and tables
Interview Tips: 💡 Know both syntaxes - method syntax is more common 💡 Explain: "Filter before sorting for better performance" 💡 Common question: "How would you add pagination?" 💡 Mention deferred execution
Problem 98: LINQ Aggregations ⭐⭐
Concepts: Sum, Average, Count, Max, Min, Aggregate, Any, All
What You'll Learn:
Calculating totals and statistics
Counting with conditions
Finding extremes
Checking existence
Custom aggregations
Handling empty sequences
Requirements: Perform statistical analysis on collections:
Calculate sums and averages
Find max/min values
Count with conditions
Check for existence
Custom aggregations
Complete Implementation:
Common Aggregation Patterns:
Handling Empty Sequences:
Bonus Challenges:
⭐⭐ Calculate standard deviation
⭐⭐ Find percentile values
⭐⭐⭐ Create custom aggregation extension method
⭐⭐⭐⭐ Build complete analytics dashboard
Real-World Usage:
Sales reports and dashboards
Financial calculations
Analytics and BI
Performance metrics
Data validation
Interview Tips: 💡 Know difference between Count() and Count 💡 Mention: "Any() is more efficient than Count() > 0" 💡 Always handle empty sequences 💡 Common question: "Calculate running total"
Problem 102: LINQ Projection (Anonymous Types) ⭐⭐
Concepts: Select, Anonymous Types, Named Tuples, Custom Projections
What You'll Learn:
Projecting to anonymous types
Transforming data shape
Selecting specific properties
Creating computed properties
Using ValueTuple
Complete Implementation:
Projection Patterns:
Bonus Challenges:
⭐⭐ Project to custom class instead of anonymous type
⭐⭐ Create DTO (Data Transfer Object) projections
⭐⭐⭐ Implement AutoMapper-like projection
⭐⭐⭐ Dynamic projection based on runtime config
Problem 103: LINQ Method vs Query Syntax ⭐⭐
Concepts: Syntax Comparison, Readability, Complex Queries, Conversion
What You'll Learn:
When to use each syntax
Converting between syntaxes
Pros and cons of each
Combining both syntaxes
Requirements: Compare the two LINQ syntaxes:
Same query in both syntaxes
Complex queries comparison
Performance considerations
Best practices
Implementation:
When to Use Each:
Conversion Guide:
Bonus Challenges:
⭐⭐ Convert complex query between syntaxes
⭐⭐ Benchmark performance differences
⭐⭐⭐ Build LINQ query builder UI
Problem 112: Lambda Expressions (Func, Action, Predicate) ⭐⭐
Concepts: Lambda Syntax, Built-in Delegates, Anonymous Functions, Closures
What You'll Learn:
Lambda expression syntax (=>)
Func<T, TResult> for returning values
Action for void methods
Predicate for boolean returns
Expression-bodied members
Closures and captured variables
Requirements: Master lambda expressions:
Basic lambda syntax
Func, Action, Predicate usage
Closures demonstration
LINQ with lambdas
Expression-bodied members
Complete Implementation:
Lambda Syntax Guide:
Built-in Delegates:
Bonus Challenges:
⭐⭐ Build calculator with lambda operations
⭐⭐ Implement strategy pattern with lambdas
⭐⭐⭐ Create fluent API using lambdas
⭐⭐⭐⭐ Expression trees and compiled lambdas
Real-World Usage:
LINQ queries
Event handlers
Async callbacks
Sorting and filtering
Dependency injection configuration
Problem 113: LINQ with Lambdas ⭐⭐
Concepts: LINQ + Lambda Integration, Query Composition, Functional Programming
What You'll Learn:
Combining LINQ and lambda expressions
Method chaining with lambdas
Complex filtering with lambdas
Query composition
Functional programming style
Requirements: Build a complete LINQ + Lambda query system:
Filter using lambda predicates
Transform using lambda selectors
Sort using lambda comparisons
Group and aggregate with lambdas
Complete Implementation:
Lambda + LINQ Patterns:
Bonus Challenges:
⭐⭐ Build query builder with lambdas
⭐⭐⭐ Create custom LINQ operators
⭐⭐⭐ Implement expression tree visitor
⭐⭐⭐⭐ Build LINQ provider
Problem 116: Basic Thread Creation ⭐⭐
Concepts: Thread, ThreadStart, Thread Lifecycle, Foreground vs Background Threads
What You'll Learn:
Creating and starting threads
Thread lifecycle (unstarted, running, stopped)
Foreground vs background threads
Thread.Sleep() and delays
Thread naming and identification
When to use threads vs tasks
Requirements: Create programs demonstrating threading:
Create and start threads
Pass parameters to threads
Use foreground and background threads
Show thread interleaving
Demonstrate thread naming
Complete Implementation:
Thread Lifecycle:
Foreground vs Background:
Thread vs Task:
Test Cases:
Bonus Challenges:
⭐⭐ Create thread pool manually
⭐⭐ Implement thread-safe counter without lock
⭐⭐⭐ Build thread scheduling system
⭐⭐⭐ Compare thread vs task performance
Real-World Usage:
Legacy code maintenance
Low-level system programming
Custom thread pools (rare)
⚠️ Modern C# uses Task instead!
Interview Tips: 💡 Mention: "Threads are legacy - use Task in modern C#" 💡 Know: "Foreground threads keep app alive" 💡 Explain: "Thread.Join() waits for completion" 💡 Important: "Background threads terminate with app"
Problem 122: Task Creation & Execution ⭐⭐
Concepts: Task, Task.Run, Task.Factory.StartNew, Task Status, Wait
What You'll Learn:
Creating tasks
Task vs Thread
Starting and waiting for tasks
Task status and lifecycle
Task.Run vs Task.Factory.StartNew
When to use each
Requirements: Create and execute tasks:
Basic task creation
Task with lambda
Wait for task completion
Check task status
Multiple task patterns
Complete Implementation:
Task Lifecycle:
Task.Run vs Task.Factory.StartNew:
Waiting for Tasks:
Bonus Challenges:
⭐⭐ Create task with custom scheduler
⭐⭐ Monitor task performance
⭐⭐⭐ Build task pool manager
⭐⭐⭐ Compare Task vs Thread performance
Interview Tips: 💡 Say: "Task is preferred over Thread in modern C#" 💡 Know: "Task.Run uses ThreadPool internally" 💡 Mention: "Task provides cancellation, progress, continuation" 💡 Important: "Use Task.Run, not Task.Factory.StartNew"
Problem 123: Task with Return Values ⭐⭐
Concepts: Task, Result Property, Generic Tasks, Return Values
What You'll Learn:
Task for returning values
Accessing Result property
Blocking vs non-blocking
Multiple tasks with results
Combining results
Requirements: Work with tasks that return values:
Create Task
Get result with .Result
Multiple tasks with different return types
Aggregate results
Handle exceptions in results
Complete Implementation:
Task vs Task:
.Result Property (⚠️ Warning):
Common Patterns:
Bonus Challenges:
⭐⭐ Build parallel aggregator
⭐⭐ Create task result cache
⭐⭐⭐ Implement map-reduce pattern
⭐⭐⭐ Build result combiner
Problem 130: Async Method Basics ⭐⭐
Concepts: async Keyword, await Keyword, Task, Async Method Signature
What You'll Learn:
async and await keywords
Async method naming convention
Return types (Task, Task, void)
Async all the way down
Common mistakes
Requirements: Master async/await fundamentals:
Create async methods
Use await keyword
Return Task and Task
Understand async void (don't use!)
Async method chaining
Complete Implementation:
async/await Rules:
Naming Convention:
Sequential vs Parallel:
Common Mistakes:
Bonus Challenges:
⭐⭐ Convert all Task examples to async/await
⭐⭐ Build async retry mechanism
⭐⭐⭐ Create async caching layer
⭐⭐⭐⭐ Implement async circuit breaker
Real-World Usage:
Every web API endpoint (ASP.NET Core)
Database calls (Entity Framework)
HTTP requests (HttpClient)
File I/O
UI event handlers
Interview Tips: 💡 Explain: "await doesn't block thread - it yields control" 💡 Know: "async Task returns T when awaited" 💡 Mention: "ConfigureAwait(false) in libraries" 💡 Critical: "Never use async void except event handlers" 💡 Common question: "Difference between Task.Result and await?"
Problem 151: Reverse String (3 Methods) ⭐⭐
Problem Statement:
Write a function that reverses a string. Implement THREE different approaches:
Using iteration
Using recursion
Using built-in methods
Examples:
Constraints:
0 ≤ string.length ≤ 10⁴
String contains ASCII characters
Approach 1: Two Pointers (Iteration)
Concept:
Use two pointers: one at start, one at end
Swap characters and move pointers toward center
Convert string to char array first (strings are immutable)
Complexity:
Time: O(n)
Space: O(n) - for char array
Hints:
Approach 2: Recursion
Concept:
Base case: empty or single character
Recursive case: first char + reverse(rest of string)
Complexity:
Time: O(n)
Space: O(n) - recursion stack + string concatenation
Hints:
Approach 3: Built-in Methods
Concept:
Use Array.Reverse() or LINQ
Hints:
Test Cases:
Interview Tips:
Show you know multiple approaches
Mention string immutability
Discuss which method is most efficient
Production code: use built-in methods
Interview: show you can implement from scratch
Problem 152: Check Anagrams ⭐⭐
Problem Statement:
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An anagram is a word formed by rearranging the letters of another word, using all original letters exactly once.
Examples:
Constraints:
1 ≤ s.length, t.length ≤ 5 × 10⁴
s and t consist of lowercase English letters
Approach 1: Sorting
Concept:
Sort both strings
Compare if sorted versions are equal
Complexity:
Time: O(n log n)
Space: O(1) or O(n) depending on sorting
Hints:
Approach 2: Frequency Map (Optimal)
Concept:
Count frequency of each character
Both strings should have same character frequencies
Complexity:
Time: O(n)
Space: O(1) - at most 26 letters
Hints:
Approach 3: Single Pass (Optimized)
Concept:
Use array of size 26 for lowercase letters
Increment for first string, decrement for second
Check if all values are zero
Hints:
Test Cases:
Common Mistakes:
Not checking lengths first (quick optimization)
Case sensitivity (problem says lowercase, but ask!)
Unicode characters (problem says English letters)
Interview Tips:
Always check lengths first (O(1) optimization)
Mention both approaches
Sorting is simpler code but slower
Hash map is optimal
Problem 153: First Non-Repeating Character ⭐⭐
Problem Statement:
Given a string s, find the first non-repeating character and return its index. If it doesn't exist, return -1.
Examples:
Constraints:
1 ≤ s.length ≤ 10⁵
s consists of lowercase English letters
Approach 1: Brute Force
Concept:
For each character, check if it appears elsewhere
Return first character that doesn't repeat
Complexity:
Time: O(n²)
Space: O(1)
Not recommended for interview!
Approach 2: Two Pass with Dictionary (Optimal)
Concept:
First pass: count frequency of each character
Second pass: find first character with frequency 1
Complexity:
Time: O(n)
Space: O(1) - at most 26 letters
Hints:
Approach 3: Array Instead of Dictionary
Concept:
Use int[26] for lowercase letters
Faster than Dictionary for this use case
Hints:
Test Cases:
Interview Tips:
Explain why two passes are needed
Mention array vs Dictionary trade-off
Array is faster for known small character set
Dictionary is more flexible for Unicode
Problem 155: String Compression (aaabb → a3b2) ⭐⭐
Problem Statement:
Implement basic string compression using the counts of repeated characters.
For example: "aabcccccaaa" becomes "a2b1c5a3"
If the compressed string is not smaller than the original, return the original string.
Examples:
Constraints:
1 ≤ s.length ≤ 10⁴
s consists of lowercase English letters
Approach: Single Pass with StringBuilder
Concept:
Iterate through string counting consecutive characters
When character changes, append count to result
Compare final length with original
Complexity:
Time: O(n)
Space: O(n) - StringBuilder
Hints:
Test Cases:
Common Mistakes:
Forgetting last character group
Not comparing lengths before returning
Using string concatenation instead of StringBuilder (slow!)
Interview Tips:
Mention StringBuilder for performance
Handle edge case: single character
Ask: "Should single occurrences show '1'?" (Yes in this version)
Problem 157: Valid Parentheses ⭐⭐
Problem Statement:
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
Valid means:
Open brackets must be closed by the same type
Open brackets must be closed in the correct order
Every close bracket has a corresponding open bracket
Examples:
Constraints:
1 ≤ s.length ≤ 10⁴
s consists of parentheses only '()[]{}'
Approach: Stack
Key Insight:
Most recent open bracket must match next close bracket
This is LIFO (Last In, First Out) → Stack!
Concept:
Push open brackets onto stack
For close bracket: check if matches top of stack
At end, stack should be empty
Complexity:
Time: O(n)
Space: O(n) - stack size
Hints:
Optimization: Use Dictionary for Matching
Test Cases:
Common Mistakes:
Not checking if stack is empty before popping
Not checking if stack is empty at the end
Forgetting edge case: empty string
Interview Tips:
Stack is THE data structure for matching problems
Explain LIFO property
Walk through example visually
Mention variations: min stack, next greater element, etc.
Problem 159: String Rotation Check ⭐⭐
Problem Statement:
Check if one string is a rotation of another.
Example: "waterbottle" is a rotation of "erbottlewat"
Examples:
Approach 1: Brute Force
Concept:
Try all possible rotations of s1
Check if any matches s2
Complexity:
Time: O(n²)
Space: O(n)
Approach 2: Clever Trick (Optimal)
Key Insight:
If s2 is rotation of s1, then s2 is substring of s1+s1!
Example: "waterbottle" + "waterbottle" = "waterbottlewaterbottle"
"erbottlewat" is substring of above!
Concept:
Check if lengths are equal (must be for rotation)
Check if s2 is substring of s1 + s1
Complexity:
Time: O(n)
Space: O(n)
Hints:
Test Cases:
Interview Tips:
Start with brute force to show understanding
Then present the clever trick
Explain why it works with example
Mention this is a common interview trick
Problem 160: Longest Common Prefix ⭐⭐
Problem Statement:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Examples:
Constraints:
1 ≤ strs.length ≤ 200
0 ≤ strs[i].length ≤ 200
strs[i] consists of lowercase English letters
Approach 1: Vertical Scanning
Concept:
Compare characters at same position across all strings
Stop when mismatch found or any string ends
Complexity:
Time: O(S) where S is sum of all characters
Space: O(1)
Hints:
Approach 2: Horizontal Scanning
Concept:
Start with first string as prefix
For each subsequent string, reduce prefix until it matches
Hints:
Test Cases:
Interview Tips:
Both approaches are valid
Vertical scanning is more intuitive
Handle edge cases: empty array, empty strings
Mention early termination optimization
Problem 162: Regex Email Validator ⭐⭐
Problem Statement:
Validate if a string is a valid email address using basic rules:
Local part (before @): letters, digits, dots, hyphens, underscores
Domain part (after @): letters, digits, dots
At least one dot in domain
No consecutive dots
Examples:
Approach 1: Manual Validation
Concept:
Check for single @
Validate local part
Validate domain part
Hints:
Approach 2: Regex Pattern
Concept:
Use regular expression pattern
Hints:
Test Cases:
Interview Tips:
Start with manual approach
Then show regex (if you know it)
Mention this is simplified version
Real email validation is VERY complex
In production: use libraries
✅ Track A Complete!
You've covered 12 essential string algorithm problems. Practice these until you can solve them confidently without hints!
Next: Track B - Array Algorithms (15 problems)
Problem 163: Two Sum ⭐⭐
[See previous example file - already completed]
Problem 167: Leaders in Array ⭐⭐
Problem Statement:
An element is a leader if it's greater than all elements to its right. Find all leaders.
Examples:
Approach: Right to Left Scan
Key Insight:
Rightmost element is always a leader
Scan from right to left, tracking max seen so far
Any element > max is a leader
Concept:
Start from right
Track maximum element seen
If current > max, it's a leader
Complexity:
Time: O(n)
Space: O(1) excluding output
Hints:
Test Cases:
Interview Tips:
Explain right-to-left approach
Mention why left-to-right is harder (O(n²))
Discuss whether order matters in output
Problem 175: Stock Buy/Sell (One Transaction) ⭐⭐
Problem Statement:
You are given an array prices where prices[i] is the price of a stock on day i.
Find maximum profit from one buy and one sell. If no profit possible, return 0.
Examples:
Approach: Single Pass
Key Insight:
Track minimum price seen so far
Calculate profit if sold today
Update maximum profit
Concept:
Keep track of lowest price
For each day, calculate: price today - lowest price
Update max profit
Complexity:
Time: O(n)
Space: O(1)
Hints:
Test Cases:
Follow-up Questions:
Multiple transactions? (Different problem - DP)
At most k transactions? (Hard DP problem)
With transaction fee? (Modified DP)
Interview Tips:
This is easier than it looks
One pass is sufficient
Explain why greedy works here
Mention follow-ups to show broader knowledge
✅ Track B Complete!
You've covered 15 essential array algorithm problems. These are the MOST common in interviews!
Next: Track C - Searching & Sorting (10 problems)
Last updated