My solutions to HackerRank problems, written in modern C# (.NET 10). Every solution has unit tests built from the problem's sample cases, and GitHub Actions runs them on each push.
- 421 problems in thirteen categories: Warmup, Implementation, Strings, Data Structures, Sorting, Search, Greedy, Dynamic Programming, Recursion, Bit Manipulation, Graph Theory, Mathematics and Game Theory
- 1172 xUnit tests covering the official samples and extra edge cases (overflow, empty results, off-by-one boundaries). Closed-form answers, such as the game theory patterns, are also checked against brute-force solvers
- Classic techniques: sliding windows, two pointers, monotonic stacks and deques, heaps, tries, Aho–Corasick, suffix arrays, Manacher, Fenwick trees (up to 3D), linked lists, BSTs, AVL trees, implicit treaps, binary lifting, difference arrays, dynamic programming (including on trees), backtracking, BFS, Dijkstra, Floyd–Warshall, union-find, minimum spanning trees, bipartite matching, difference constraints, Karp's minimum mean cycle, Lucas's theorem, Miller–Rabin, Sprague–Grundy, modular arithmetic, bit tricks and closed-form math. Most solutions run in O(n) or O(n log n)
- Every solution has a doc comment with the problem statement and a link to the original challenge
hackerrank-exercises/
├── src/HackerRank.Solutions/ # Class library: one static class per problem
│ ├── Warmup/
│ ├── Implementation/
│ ├── Strings/
│ ├── DataStructures/
│ ├── Sorting/
│ ├── Search/
│ ├── Greedy/
│ ├── DynamicProgramming/
│ ├── Recursion/
│ ├── BitManipulation/
│ ├── GraphTheory/
│ ├── Mathematics/
│ └── GameTheory/
├── tests/HackerRank.Solutions.Tests/ # xUnit tests, one file per category
├── .github/workflows/build.yml # CI: build and test on every push / PR
└── HackerRank.sln
Each problem is a static class with a single Solve method:
// src/HackerRank.Solutions/Strings/SuperReducedString.cs
public static class SuperReducedString
{
public static string Solve(string s)
{
var stack = new StringBuilder(s.Length);
foreach (var c in s)
{
if (stack.Length > 0 && stack[^1] == c)
stack.Length--;
else
stack.Append(c);
}
return stack.Length > 0 ? stack.ToString() : "Empty String";
}
}Requires the .NET 10 SDK.
git clone https://github.com/dejanciev-dev/hackerrank-exercises.git
cd hackerrank-exercises
dotnet testTo run the tests for one category or one problem:
dotnet test --filter "FullyQualifiedName~StringsTests"
dotnet test --filter "FullyQualifiedName~ClimbingTheLeaderboard"| Problem | Difficulty | Approach | Solution |
|---|---|---|---|
| Solve Me First | Easy | Arithmetic | SolveMeFirst.cs |
| Simple Array Sum | Easy | Linear scan | SimpleArraySum.cs |
| Compare the Triplets | Easy | Pairwise comparison | CompareTheTriplets.cs |
| A Very Big Sum | Easy | 64-bit accumulation | AVeryBigSum.cs |
| Diagonal Difference | Easy | Single pass over both diagonals | DiagonalDifference.cs |
| Plus Minus | Easy | Counting, invariant formatting | PlusMinus.cs |
| Staircase | Easy | String building | Staircase.cs |
| Mini-Max Sum | Easy | Total minus max / min | MiniMaxSum.cs |
| Birthday Cake Candles | Easy | Single pass max-count | BirthdayCakeCandles.cs |
| Time Conversion | Easy | String parsing | TimeConversion.cs |
| Problem | Difficulty | Approach | Solution |
|---|---|---|---|
| Ice Cream Parlor | Easy | Two-sum with a dictionary | IceCreamParlor.cs |
| Missing Numbers | Easy | Frequency balance | MissingNumbers.cs |
| Sherlock and Array | Easy | Prefix sums | SherlockAndArray.cs |
| Pairs | Medium | HashSet lookup, O(n) | Pairs.cs |
| Minimum Loss | Medium | Sort, check adjacent pairs | MinimumLoss.cs |
| Connected Cells in a Grid | Medium | Iterative flood fill | ConnectedCellsInAGrid.cs |
| Hackerland Radio Transmitters | Medium | Greedy placement | HackerlandRadioTransmitters.cs |
| Count Triplets | Medium | Left / right counts per middle term | CountTriplets.cs |
| Gridland Metro | Medium | Merge intervals per row | GridlandMetro.cs |
| KnightL on a Chessboard | Medium | BFS per move pair | KnightLOnAChessboard.cs |
| Count Luck | Medium | BFS parents, count forks on the path | CountLuck.cs |
| Cut the Tree | Medium | Subtree sums | CutTheTree.cs |
| Maximum Subarray Sum | Hard | Prefix sums in a sorted set | MaximumSubarraySum.cs |
| Red Knight's Shortest Path | Medium | BFS from target, greedy walk by priority | RedKnightsShortestPath.cs |
| Triple sum | Medium | Dedupe, sort, binary search per q | TripleSum.cs |
| Minimum Time Required | Medium | Binary search on days | MinimumTimeRequired.cs |
| Similar Pair | Advanced | DFS + Fenwick tree of ancestors | SimilarPair.cs |
| Bike Racers | Hard | Binary search + bipartite matching | BikeRacers.cs |
| Playing With Numbers | Hard | Sorted prefix sums + running shift | AbsoluteElementSums.cs |
| Gena Playing Hanoi | Medium | BFS over base-4 states | GenaPlayingHanoi.cs |
| Problem | Difficulty | Approach | Solution |
|---|---|---|---|
| Minimum Absolute Difference in an Array | Easy | Sort + adjacent scan | MinimumAbsoluteDifference.cs |
| Luck Balance | Easy | Lose the k luckiest important contests | LuckBalance.cs |
| Grid Challenge | Easy | Sort rows, check columns | GridChallenge.cs |
| Jim and the Orders | Easy | Sort by completion time | JimAndTheOrders.cs |
| Max Min | Medium | Sort + sliding window | MaxMin.cs |
| Greedy Florist | Medium | Most expensive first, round-robin | GreedyFlorist.cs |
| Marc's Cakewalk | Easy | Largest calories first | MarcsCakewalk.cs |
| Sherlock and The Beast | Easy | Maximize leading 5s | SherlockAndTheBeast.cs |
| Priyanka and Toys | Easy | Sort + interval cover | PriyankaAndToys.cs |
| Permuting Two Arrays | Easy | Opposite-order pairing | PermutingTwoArrays.cs |
| Beautiful Pairs | Easy | Multiset matching | BeautifulPairs.cs |
| Largest Permutation | Easy | Position index, O(n) swaps | LargestPermutation.cs |
| Chief Hopper | Hard | Work backwards, O(n) | ChiefHopper.cs |
| Maximum Perimeter Triangle | Easy | Sort descending, first valid triple | MaximumPerimeterTriangle.cs |
| Flipping the Matrix | Medium | Max of each mirror quartet | FlippingTheMatrix.cs |
| Goodland Electricity | Medium | Rightmost plant that covers | GoodlandElectricity.cs |
| Cutting Boards | Hard | Most expensive cut first | CuttingBoards.cs |
| Reverse Shuffle Merge | Advanced | Monotonic stack with skip budget | ReverseShuffleMerge.cs |
| Sherlock and MiniMax | Hard | Range ends + adjacent midpoints | SherlockAndMinimax.cs |
| Making Candies | Hard | Buy balanced, track "wait from here" | MakingCandies.cs |
| Cloudy Day | Medium | Sweep line, credit single-cloud towns | CloudyDay.cs |
| Team Formation | Advanced | Extend the smallest team ending at skill - 1 | TeamFormation.cs |
| Interval Selection | Medium | By right end, track the doubly-covered point | IntervalSelection.cs |
| Problem | Difficulty | Approach | Solution |
|---|---|---|---|
| The Coin Change Problem | Medium | Combinations DP, O(n · coins) | CoinChange.cs |
| Fibonacci Modified | Medium | Iterative BigInteger | FibonacciModified.cs |
| Equal | Medium | Reverse the operation + 5/2/1 greedy | Equal.cs |
| Sam and Substrings | Medium | Running suffix sum, mod 10⁹+7 | SamAndSubstrings.cs |
| Stock Maximize | Medium | Backward scan of future maximum | StockMaximize.cs |
| Max Array Sum | Medium | Non-adjacent DP, O(1) memory | MaxArraySum.cs |
| Candies | Medium | Two directional passes | Candies.cs |
| Sherlock and Cost | Medium | Two-state DP (low / high) | SherlockAndCost.cs |
| Abbreviation | Medium | 2D reachability DP | Abbreviation.cs |
| Knapsack | Medium | Unbounded subset-sum DP | Knapsack.cs |
| The Longest Increasing Subsequence | Advanced | Patience sorting, O(n log n) | LongestIncreasingSubsequence.cs |
| The Maximum Subarray | Medium | Kadane + sum of positives | MaximumSubarray.cs |
| Red John is Back | Medium | Tiling recurrence + sieve | RedJohnIsBack.cs |
| Construct the Array | Medium | Two-state DP by symmetry | ConstructTheArray.cs |
| The Mandragora Forest | Medium | Sort + suffix sums | MandragoraForest.cs |
| Lego Blocks | Medium | All walls minus walls with a first break | LegoBlocks.cs |
| The Longest Common Subsequence | Medium | LCS table + backtrack | LongestCommonSubsequence.cs |
| Bricks Game | Medium | Suffix sum minus opponent's best | BricksGame.cs |
| Summing Pieces | Medium | Per-element coefficients, O(n) | SummingPieces.cs |
| Play with words | Medium | LPS table + best split | PlayWithWords.cs |
| The Indian Job | Medium | Subset sum | TheIndianJob.cs |
| Angry Children 2 | Hard | Sorted window, weighted prefix sums | AngryChildren2.cs |
| Mr K marsh | Hard | Row pairs + column scan | MrKMarsh.cs |
| Kingdom Division | Hard | Tree DP: happy / lonely states | KingdomDivision.cs |
| Two Robots | Medium | State = the idle robot's position | TwoRobots.cs |
| Substring Diff | Medium | Sliding window per diagonal | SubstringDiff.cs |
| Grid Walking | Medium | 1-D walks combined with binomials | GridWalking.cs |
| Wet Shark and Two Subsequences | Medium | Knapsack by (length, sum) | WetSharkAndTwoSubsequences.cs |
| Prime XOR | Medium | Even/odd counts per value, DP over XOR | PrimeXor.cs |
| Coin on the Table | Medium | 0-1 BFS over (cell, time) | CoinOnTheTable.cs |
| Dorsey Thief | Medium | Exact-weight 0/1 knapsack | DorseyThief.cs |
| Fair Cut | Medium | Sorted DP with ± contributions | FairCut.cs |
| Decibinary Numbers | Hard | Counting table, digit-by-digit ranking | DecibinaryNumbers.cs |
| Problem | Difficulty | Approach | Solution |
|---|---|---|---|
| Recursive Digit Sum | Medium | Sum once, multiply by k | RecursiveDigitSum.cs |
| The Power Sum | Medium | Include / exclude recursion | ThePowerSum.cs |
| Recursion: Fibonacci Numbers | Easy | Memoized recursion | FibonacciNumbers.cs |
| Recursion: Davis' Staircase | Medium | Memoized three-way recursion | DavisStaircase.cs |
| Password Cracker | Medium | DFS with dead-end memo | PasswordCracker.cs |
| Crossword Puzzle | Medium | Backtracking over slots | CrosswordPuzzle.cs |
| Nikita and the Game | Medium | Binary-search the half-sum split | NikitaAndTheGame.cs |
| Arithmetic Expressions | Hard | Search over (position, remainder mod 101) | ArithmeticExpressions.cs |
| K Factorization | Hard | BFS over divisors, greedy smallest step | KFactorization.cs |
| Problem | Difficulty | Approach | Solution |
|---|---|---|---|
| Lonely Integer | Easy | XOR cancellation | LonelyInteger.cs |
| Maximizing XOR | Easy | Highest differing bit, O(1) | MaximizingXor.cs |
| Sum vs XOR | Easy | 2^(zero bits) | SumVsXor.cs |
| Flipping Bits | Easy | 32-bit complement | FlippingBits.cs |
| Counter Game | Medium | popcount(n - 1) parity | CounterGame.cs |
| The Great XOR | Medium | All-ones mask XOR x | TheGreatXor.cs |
| Sansa and XOR | Medium | Occurrence-count parity | SansaAndXor.cs |
| AND Product | Medium | Common bit prefix | AndProduct.cs |
| Xor-sequence | Medium | Period-8 prefix XOR, O(1) | XorSequence.cs |
| Cipher | Medium | Adjacent XOR undoes the shifts | Cipher.cs |
| Yet Another Minimax Problem | Medium | Split on highest differing bit | YetAnotherMinimax.cs |
| Winning Lottery Ticket | Medium | Digit masks, 1024² pairs | WinningLotteryTicket.cs |
| Xoring Ninja | Medium | OR of all · 2^(n-1) | XoringNinja.cs |
| 2's complement | Advanced | Per-bit counting, negatives as complements | TwosComplement.cs |
| XOR Matrix | Hard | Power-of-two jumps over GF(2) | XorMatrix.cs |
| Xor and Sum | Hard | x ⊕ y = x + y - 2(x ∧ y), per-bit counts | XorAndSum.cs |
| A or B | Medium | Required changes, then shrink A from the top | AOrB.cs |
| Changing Bits | Hard | Carry from the nearest equal-bit position | ChangingBits.cs |
| Problem | Difficulty | Approach | Solution |
|---|---|---|---|
| Game of Stones | Easy | Losing positions: n mod 7 ∈ {0, 1} | GameOfStones.cs |
| Tower Breakers | Easy | Mirror strategy | TowerBreakers.cs |
| A Chessboard Game | Easy | Period-4 losing squares | ChessboardGame.cs |
| Introduction to Nim Game | Easy | Nim-sum | IntroductionToNim.cs |
| Misère Nim | Medium | Nim-sum, all-ones special case | MisereNim.cs |
| Nimble Game | Medium | XOR of odd-count indices | NimbleGame.cs |
| Poker Nim | Easy | Additions are reversible: plain Nim | PokerNim.cs |
| Tower Breakers, Revisited! | Medium | Grundy = prime factor count | TowerBreakersRevisited.cs |
| Alice and Bob's Silly Game | Medium | Parity of the prime count | AliceAndBobsSillyGame.cs |
| Zero-Move Nim | Medium | Grundy n ± 1 by parity | ZeroMoveNim.cs |
| Kitty and Katty | Medium | Parity of the move count | KittyAndKatty.cs |
| New Year Game | Medium | Residue counts mod 3 | NewYearGame.cs |
| Powers Game | Medium | 2^4 ≡ -1 (mod 17) pairing | PowersGame.cs |
| Bowling Pins | Advanced | Grundy numbers of pin runs | BowlingPins.cs |
| Chessboard Game, Again! | Medium | XOR of per-coin Grundy numbers | ChessboardGameAgain.cs |
| Permutation game | Medium | Bitmask memoisation | PermutationGame.cs |
| Fun Game | Medium | Greedy by a[i] + b[i] | FunGame.cs |
| Stone Division | Hard | Grundy over divisors | StoneDivision.cs |
| Deforestation | Hard | Green Hackenbush, colon principle | Deforestation.cs |
| Chocolate in Box | Medium | Piles where a ⊕ X < a | ChocolateInBox.cs |
| Tower Breakers, Again! | Medium | Grundy over divisors | TowerBreakersAgain.cs |
| Play on benders | Hard | Grundy numbers on a DAG | PlayOnBenders.cs |
| Manasa and Prime game | Hard | Periodic Grundy sequence | ManasaAndPrimeGame.cs |
- Add a static class under the matching category folder in
src/HackerRank.Solutions/, with a<summary>that describes the problem and links to it. - Add tests with the problem's sample cases to the matching
*Tests.csfile. - Run
dotnet testand add a row to the table above.
Solutions are my own work. Problem statements belong to HackerRank.