A comprehensive collection of Java coding problems, algorithms, data structures, and design patterns for interview preparation and skill development. This repository contains solutions to problems from CodeChef, Codility, and common technical interview questions.
- Overview
- Project Structure
- Categories
- Getting Started
- Running Tests
- Topics Covered
- Contributing
- License
This repository serves as a practical learning resource for Java developers preparing for technical interviews or looking to strengthen their problem-solving skills. Each solution is implemented with clarity and includes test cases where applicable.
Technology Stack:
- Java (JDK 8+)
- Maven 3.x
- JUnit 4.13.1
java-coding-practice/
├── src/
│ ├── main/java/
│ │ ├── codechef/ # CodeChef competition problems
│ │ └── com/java/recruitme/
│ │ ├── algo/ # Core algorithms & data structures
│ │ ├── threads/ # Concurrency & multithreading
│ │ ├── comparator/ # Comparator implementations
│ │ ├── exceptions/ # Exception handling patterns
│ │ ├── characterCount/ # String manipulation problems
│ │ ├── expressionValidator/ # Expression parsing & validation
│ │ ├── immutableCollection/ # Immutable design patterns
│ │ ├── equalityProblem/ # equals() & hashCode() implementations
│ │ ├── innerclass/ # Inner class patterns
│ │ ├── jmx/ # Java Management Extensions
│ │ ├── kafka/ # Kafka client examples
│ │ └── primes/ # Prime number algorithms
│ └── test/java/ # Unit tests and practice problems
└── pom.xml # Maven configuration
| Problem | Description | Difficulty |
|---|---|---|
| BinaryTree.java | Binary tree traversals (In/Pre/Post/Level order), max path sum | Medium |
| DijkstraAlgo.java | Shortest path algorithm for weighted graphs | Medium |
| ManachersAlgo.java | Longest palindromic substring in linear time | Hard |
| StringKMPSearch.java | Knuth-Morris-Pratt pattern matching | Medium |
| ImplementQueueUsingStack.java | Queue implementation using two stacks | Easy |
| StackObjectUsingSingleArray.java | Multiple stacks in a single array | Medium |
| ReverseSubArray.java | Array manipulation techniques | Easy |
| SubMatrixSum.java | 2D matrix range sum queries | Medium |
| Problem | Description | Key Concepts |
|---|---|---|
| ProducerConsumerDemo.java | Classic producer-consumer pattern | wait/notify, synchronization |
| PrintEvenOdd.java | Print even/odd numbers in sequence | Thread coordination |
| Printevenoddsequentialusinglock.java | Even/odd printing with ReentrantLock | Explicit locks |
| Printoddevenusinglockonobect.java | Even/odd with object-level locking | Monitor locks |
| InterThreadCommunication.java | Thread communication patterns | wait/notify mechanisms |
| ExecutorServiceSample.java | Thread pool management | ExecutorService, Callable, Future |
| ArraySumCalculator.java | Parallel array processing | Fork/Join framework |
Test Examples: Thread safety, data corruption prevention, semaphores, file reading concurrency
- CharacterCount.java - Character frequency analysis
- Convertstringtointeger.java - String to integer conversion (atoi implementation)
- ConvertIntegerToRoman.java - Integer to Roman numeral conversion
- ExpressionValidator.java - Balanced parentheses/bracket validation
- Comparator.java / ComparatorImpl.java - Custom comparator implementations
- Player.java - equals() and hashCode() contract demonstration
- CopyConstructor.java - Copy constructor pattern
- InnerClass.java - Inner class usage patterns
- ReflectionUsingString.java - Java Reflection API examples
- ErraticService.java / ErraticServiceImpl.java - Exception handling patterns
- StackTraceImpl.java - Stack trace analysis and manipulation
- Custom Exceptions: RandomException, RandomError, MethodNotImplementedException
- ImmutableCollection.java - Creating immutable collections
- FailSafe.java - Fail-safe iterator patterns
- Prime.java - Prime number generation and checking algorithms
CodeChef:
Codechef_ZCO15004.java- ZCO 2015 problemCodilityAdjacentString.java- Codility string manipulation challenge
All programs run automatically on every push! 🎉
- Go to the Actions tab in this repository
- Click on the latest workflow run (green ✅ = success, red ❌ = failures)
- Click on the "build-and-test" job
- Expand the workflow steps to see outputs:
- "Build with Maven" - Compilation results
- "Run all tests" - JUnit test execution
- "Run sample programs" - Individual program outputs
Programs that run automatically:
- Binary Tree traversals and algorithms
- Dijkstra's shortest path algorithm
- Producer-Consumer multithreading demo
- Character count analysis
- Prime number generation
You can also trigger the workflow manually:
- Go to Actions tab
- Click "Java CI - Run All Programs" on the left
- Click "Run workflow" button
- Select branch and click "Run workflow"
Want to run a specific program? You can now execute ANY of the 27 programs individually!
- Navigate to the Actions tab
- Select "Run Java Program On-Demand" from the left sidebar
- Configure your run:
- Program: Choose from dropdown (27 programs available!)
- Input: Provide input for programs that need it (see table below)
- Timeout: Set execution timeout (default: 30s, max: 300s)
- Click "Run workflow"
- View results: Click on the workflow run, then expand "Run selected program" step
| Program | Input | Format | Example |
|---|---|---|---|
| Convertstringtointeger | ✅ Required | String number | 1234 |
| ConvertIntegerToRoman | ✅ Required | Integer (1-4999) | 2024 |
| Codechef_ZCO15004 | ✅ Required | Multi-line stdin | See example below |
| CodilityAdjacentString | ⭕ Optional | Test string | ab??aba |
| All threading programs | ⏱️ Timeout | Use 10-30s | Infinite loops |
| ExecutorServiceSample | External file needed | Expected failure | |
| All other programs | ❌ None | Self-contained | Leave blank |
- Select "BinaryTree - Tree traversals and operations"
- Leave input blank
- Use default 30s timeout
- Click "Run workflow"
- ✅ See tree traversal output!
- Select "ConvertIntegerToRoman - Integer to Roman (REQUIRES INPUT)"
- Enter input:
2024 - Use default 30s timeout
- Click "Run workflow"
- ✅ Output shows:
MMXXIV
- Select "ProducerConsumerDemo - Producer-consumer (infinite, 10s recommended)"
- Leave input blank
- Set timeout:
10seconds - Click "Run workflow"
- ✅ See 10 seconds of producer-consumer interaction, then graceful termination
- Select "Codechef_ZCO15004 - CodeChef problem (REQUIRES STDIN)"
- Enter multi-line input (use actual newlines or
\n):3 2 5 4 3 6 2 - Use default 30s timeout
- Click "Run workflow"
- ✅ See calculated rectangular area!
- BinaryTree - Tree traversals, max path sum
- DijkstraAlgo - Shortest path algorithm
- ManachersAlgo - Longest palindrome (linear time)
- StringKMPSearch - KMP pattern matching
- ImplementQueueUsingStack - Queue using two stacks
- ReverseSubArray - Array manipulation
- SubMatrixSum - 2D matrix range queries
⏱️ Note: These run infinitely. Use 10-30 second timeout.
- ProducerConsumerDemo - Classic producer-consumer
- ProducerConsumerMain - Producer-consumer variant
- PrintEvenOdd - Even/odd sequence printing
- Printevenoddsequentialusinglock - Even/odd with ReentrantLock
- Printoddevenusinglockonobect - Even/odd with monitor locks
- InterThreadCommunication - Piped stream communication
- ExecutorServiceSample - Thread pool (requires external file)
- CharacterCount - Character frequency analysis
- Convertstringtointeger - atoi implementation (needs input)
- ConvertIntegerToRoman - Integer to Roman numeral (needs input)
- ExpressionValidatorImpl - Balanced bracket validation
- Prime - Prime number generation
- ReflectionUsingString - Reflection API demo
- ComparatorImpl - Custom comparator
- Player - equals/hashCode contract
- InnerClass - Inner class patterns
- CopyConstructor - Copy constructor pattern
- FailSafe - Fail-safe iterator
- CodilityAdjacentString - String manipulation challenge
- Codechef_ZCO15004 - Rectangular area calculation (needs stdin)
"ERROR: This program requires input"
- Check the input requirements table above
- Provide appropriate input in the "Input" field
"Program exceeded timeout"
- Increase timeout value (especially for threading programs)
- Infinite loop programs need 10-30s to demonstrate behavior
ExecutorServiceSample fails
- This is EXPECTED - program requires external file not in repository
- Demonstrates graceful error handling
Tips:
- Threading programs show interesting behavior in 10-30 seconds
- Use short timeouts (10-15s) to save GitHub Actions minutes
- All programs requiring input are clearly marked in dropdown
- Execution logs show detailed output including print statements
- Java Development Kit (JDK) 8 or higher
- Apache Maven 3.x
- Git (for cloning the repository)
# Clone the repository
git clone git@github.com:anishk835/sample-question.git
cd sample-question
# Build the project
mvn clean install
# Run all tests
mvn testMost classes have a main() method for demonstration:
# Compile and run a specific class
mvn compile
mvn exec:java -Dexec.mainClass="com.java.recruitme.algo.BinaryTree"
mvn exec:java -Dexec.mainClass="com.java.recruitme.algo.DijkstraAlgo"
mvn exec:java -Dexec.mainClass="com.java.recruitme.threads.ProducerConsumerDemo"The project uses JUnit 4.13.1 for testing.
# Run all tests
mvn test
# Run a specific test class
mvn test -Dtest=CharacterCountTest
mvn test -Dtest=ErraticServiceTest
mvn test -Dtest=ExpressionValidatorTest
# Run tests with verbose output
mvn test -XTests are organized under src/test/java/:
- Unit Tests - Test individual components and algorithms
- Thread Tests - Concurrent programming scenarios and edge cases
- Integration Tests - Service and component interaction tests
- Binary Trees (traversal, max path sum)
- Stacks and Queues
- Arrays and Matrices
- Graphs (Dijkstra's algorithm)
- Searching: KMP string search, binary search
- String Processing: Manacher's algorithm (longest palindrome)
- Graph Algorithms: Dijkstra's shortest path
- Dynamic Programming: Max path sum, subarray problems
- Thread synchronization (synchronized, wait/notify)
- ReentrantLock and explicit locking
- Producer-Consumer pattern
- Thread pools and ExecutorService
- Semaphores
- Thread-safe collections
- Race condition prevention
- Factory pattern
- Builder pattern (immutable objects)
- Iterator pattern (fail-safe)
- Observer pattern
- Generics
- Collections Framework
- Exception handling
- Reflection API
- JMX (Java Management Extensions)
- Comparators and Comparable
- Apache Kafka basics
Beginners:
- Start with basic data structures (BinaryTree, ImplementQueueUsingStack)
- Practice string manipulation (CharacterCount, Convertstringtointeger)
- Understand OOP concepts (Player, CopyConstructor, Comparator)
Intermediate:
- Explore algorithms (DijkstraAlgo, StringKMPSearch)
- Master exception handling (ErraticService, StackTrace)
- Learn concurrent programming basics (ProducerConsumerDemo, PrintEvenOdd)
Advanced:
- Study complex algorithms (ManachersAlgo, SubMatrixSum)
- Deep dive into concurrency (ExecutorService, thread safety patterns)
- Explore advanced Java (Reflection, JMX, Kafka integration)
Contributions are welcome! If you'd like to add new problems or improve existing solutions:
- Fork the repository
- Create a feature branch (
git checkout -b feature/new-algorithm) - Add your solution with tests
- Commit your changes (
git commit -m 'Add new algorithm: XYZ') - Push to the branch (
git push origin feature/new-algorithm) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
Author: Anish Kumar GitHub: @anishk835
- CodeChef and Codility for problem inspirations
- Java community for best practices and patterns
- Contributors and reviewers
⭐ Star this repository if you find it helpful!
Last updated: March 2026