Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

11 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Java Coding Practice

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.

๐Ÿ“‹ Table of Contents

๐ŸŽฏ Overview

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

๐Ÿ“ Project Structure

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

๐Ÿ“š Categories

๐Ÿ”ข Algorithms & Data Structures (algo/)

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

๐Ÿงต Concurrency & Multithreading (threads/)

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

๐Ÿ”ค String & Character Problems

  • 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

๐ŸŽฏ Object-Oriented Design

  • 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

๐Ÿ› Exception Handling & Error Management

  • ErraticService.java / ErraticServiceImpl.java - Exception handling patterns
  • StackTraceImpl.java - Stack trace analysis and manipulation
  • Custom Exceptions: RandomException, RandomError, MethodNotImplementedException

๐Ÿงช Java Core Concepts

  • ImmutableCollection.java - Creating immutable collections
  • FailSafe.java - Fail-safe iterator patterns
  • Prime.java - Prime number generation and checking algorithms

๐Ÿ† Competitive Programming

CodeChef:

  • Codechef_ZCO15004.java - ZCO 2015 problem
  • CodilityAdjacentString.java - Codility string manipulation challenge

๐Ÿค– Automated Program Execution on GitHub

All programs run automatically on every push! ๐ŸŽ‰

View Program Outputs Online

  1. Go to the Actions tab in this repository
  2. Click on the latest workflow run (green โœ… = success, red โŒ = failures)
  3. Click on the "build-and-test" job
  4. 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

Manual Trigger

You can also trigger the workflow manually:

  1. Go to Actions tab
  2. Click "Java CI - Run All Programs" on the left
  3. Click "Run workflow" button
  4. Select branch and click "Run workflow"

๐ŸŽฎ Run Individual Programs On-Demand

Want to run a specific program? You can now execute ANY of the 27 programs individually!

How to Use

  1. Navigate to the Actions tab
  2. Select "Run Java Program On-Demand" from the left sidebar
  3. 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)
  4. Click "Run workflow"
  5. View results: Click on the workflow run, then expand "Run selected program" step

Program Input Requirements

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 โš ๏ธ May fail External file needed Expected failure
All other programs โŒ None Self-contained Leave blank

Quick Start Examples

Example 1: Run BinaryTree (No Input)

  1. Select "BinaryTree - Tree traversals and operations"
  2. Leave input blank
  3. Use default 30s timeout
  4. Click "Run workflow"
  5. โœ… See tree traversal output!

Example 2: Convert Integer to Roman (Needs Input)

  1. Select "ConvertIntegerToRoman - Integer to Roman (REQUIRES INPUT)"
  2. Enter input: 2024
  3. Use default 30s timeout
  4. Click "Run workflow"
  5. โœ… Output shows: MMXXIV

Example 3: Producer-Consumer Demo (Infinite Loop)

  1. Select "ProducerConsumerDemo - Producer-consumer (infinite, 10s recommended)"
  2. Leave input blank
  3. Set timeout: 10 seconds
  4. Click "Run workflow"
  5. โœ… See 10 seconds of producer-consumer interaction, then graceful termination

Example 4: CodeChef Problem (Stdin Input)

  1. Select "Codechef_ZCO15004 - CodeChef problem (REQUIRES STDIN)"
  2. Enter multi-line input (use actual newlines or \n):
    3
    2 5
    4 3
    6 2
    
  3. Use default 30s timeout
  4. Click "Run workflow"
  5. โœ… See calculated rectangular area!

Available Programs by Category

๐Ÿ”ข Algorithms & Data Structures (7 programs)

  • 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

๐Ÿงต Threading & Concurrency (7 programs)

โฑ๏ธ 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)

๐Ÿ”ค String & Utilities (6 programs)

  • 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

๐ŸŽฏ OOP & Design Patterns (5 programs)

  • ComparatorImpl - Custom comparator
  • Player - equals/hashCode contract
  • InnerClass - Inner class patterns
  • CopyConstructor - Copy constructor pattern
  • FailSafe - Fail-safe iterator

๐Ÿ† Competitive Programming (2 programs)

  • CodilityAdjacentString - String manipulation challenge
  • Codechef_ZCO15004 - Rectangular area calculation (needs stdin)

Troubleshooting

"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

๐Ÿš€ Getting Started

Prerequisites

  • Java Development Kit (JDK) 8 or higher
  • Apache Maven 3.x
  • Git (for cloning the repository)

Installation

# 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 test

Running Individual Examples

Most 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"

๐Ÿงช Running Tests

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 -X

Test Coverage

Tests 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

๐Ÿ“– Topics Covered

Data Structures

  • Binary Trees (traversal, max path sum)
  • Stacks and Queues
  • Arrays and Matrices
  • Graphs (Dijkstra's algorithm)

Algorithms

  • 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

Java Concurrency

  • Thread synchronization (synchronized, wait/notify)
  • ReentrantLock and explicit locking
  • Producer-Consumer pattern
  • Thread pools and ExecutorService
  • Semaphores
  • Thread-safe collections
  • Race condition prevention

Design Patterns

  • Factory pattern
  • Builder pattern (immutable objects)
  • Iterator pattern (fail-safe)
  • Observer pattern

Java Core

  • Generics
  • Collections Framework
  • Exception handling
  • Reflection API
  • JMX (Java Management Extensions)
  • Comparators and Comparable

Integration Technologies

  • Apache Kafka basics

๐Ÿ’ก Learning Path

Beginners:

  1. Start with basic data structures (BinaryTree, ImplementQueueUsingStack)
  2. Practice string manipulation (CharacterCount, Convertstringtointeger)
  3. Understand OOP concepts (Player, CopyConstructor, Comparator)

Intermediate:

  1. Explore algorithms (DijkstraAlgo, StringKMPSearch)
  2. Master exception handling (ErraticService, StackTrace)
  3. Learn concurrent programming basics (ProducerConsumerDemo, PrintEvenOdd)

Advanced:

  1. Study complex algorithms (ManachersAlgo, SubMatrixSum)
  2. Deep dive into concurrency (ExecutorService, thread safety patterns)
  3. Explore advanced Java (Reflection, JMX, Kafka integration)

๐Ÿค Contributing

Contributions are welcome! If you'd like to add new problems or improve existing solutions:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/new-algorithm)
  3. Add your solution with tests
  4. Commit your changes (git commit -m 'Add new algorithm: XYZ')
  5. Push to the branch (git push origin feature/new-algorithm)
  6. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ“ž Contact

Author: Anish Kumar GitHub: @anishk835

๐ŸŽ“ Acknowledgments

  • 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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages