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.
- 458 problems in thirteen categories: Warmup, Implementation, Strings, Data Structures, Sorting, Search, Greedy, Dynamic Programming, Recursion, Bit Manipulation, Graph Theory, Mathematics and Game Theory
- 1381 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, palindromic trees, Fenwick trees (up to 3D), segment trees with range updates, binary tries, 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, segmented sieves, digit DP, Miller–Rabin, Sprague–Grundy, staircase Nim, 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 |
| Beautiful Quadruples | Medium | Sweep the third value, XOR-count table of the first two | BeautifulQuadruples.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 |
| Bonetrousle | Medium | Start from 1..k and raise the largest boxes | Bonetrousle.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 |
| LCS Returns | Hard | Prefix and suffix LCS tables meeting at the insertion | LcsReturns.cs |
| Square Subsequences | Hard | Split point + common-subsequence pair counting, O(n³) | SquareSubsequences.cs |
| Lucky Numbers | Hard | Digit DP over (digit sum, square sum) | LuckyNumbers.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 |
| What's Next? | Medium | Rewrite the last runs: 0 1^k 0^m → 1 0^(m+1) 1^(k−1) | WhatsNext.cs |
| Maximum Xor | Medium | Binary trie, greedy opposite-bit walk | MaximumXor.cs |
| Problem | Difficulty | Approach | Solution |
|---|---|---|---|
| Find the Point | Easy | Reflection: 2q - p | FindThePoint.cs |
| Maximum Draws | Easy | Pigeonhole | MaximumDraws.cs |
| Handshake | Easy | n choose 2 | Handshake.cs |
| Minimum Height Triangle | Easy | Integer ceiling | MinimumHeightTriangle.cs |
| Army Game | Easy | ⌈n/2⌉ · ⌈m/2⌉ | ArmyGame.cs |
| Connecting Towns | Easy | Product mod 1234567 | ConnectingTowns.cs |
| Halloween Party | Easy | Split cuts evenly | HalloweenParty.cs |
| Leonardo's Prime Factors | Easy | Primorials, overflow-safe | LeonardosPrimeFactors.cs |
| Summing the N series | Easy | Telescopes to n² | SummingTheNSeries.cs |
| Best Divisor | Easy | Divisor pairs up to √n | BestDivisor.cs |
| Restaurant | Easy | GCD-sized squares | Restaurant.cs |
| Reverse Game | Easy | Alternating final order, O(1) | ReverseGame.cs |
| Strange Grid Again | Easy | Closed form | StrangeGrid.cs |
| Cutting Paper Squares | Easy | Each cut adds one piece | CuttingPaperSquares.cs |
| Diwali Lights | Easy | 2^n - 1, fast exponentiation | DiwaliLights.cs |
| Constructing a Number | Easy | Digit sum mod 3 | ConstructingANumber.cs |
| Sherlock and Divisors | Easy | Divisors of n / 2 | SherlockAndDivisors.cs |
| Filling Jars | Easy | Only the total matters | FillingJars.cs |
| Special Multiple | Medium | BFS over remainders | SpecialMultiple.cs |
| Is Fibo | Medium | Walk the sequence | IsFibo.cs |
| Possible Path | Medium | Moves preserve the GCD | PossiblePath.cs |
| Fibonacci Finding (easy) | Medium | Fast doubling, O(log n) | FibonacciFinding.cs |
| Points On a Line | Easy | Shared x or shared y | PointsOnALine.cs |
| Triangle Numbers | Medium | Period-4 parity pattern | TriangleNumbers.cs |
| Sherlock and Permutations | Medium | C(n + m - 1, n) | SherlockAndPermutations.cs |
| Matrix Tracing | Hard | Lattice paths, C(m + n - 2, m - 1) | MatrixTracing.cs |
| nCr Table | Medium | Pascal row mod 10^9 | NcrTable.cs |
| K Candy Store | Medium | Stars and bars | KCandyStore.cs |
| A Chocolate Fiesta | Medium | Half the odd subsets are even | ChocolateFiesta.cs |
| Bus Station | Medium | Divisors of the total, greedy check | BusStation.cs |
| Most Distant | Medium | Axis extremes | MostDistant.cs |
| Polar Angles | Medium | Exact half-plane + cross product sort | PolarAngles.cs |
| John and GCD list | Easy | Neighbouring LCMs | JohnAndGcdList.cs |
| Easy GCD | Medium | Prime factors of the gcd | EasyGcd.cs |
| Identify Smith Numbers | Easy | Digit sums of prime factors | SmithNumbers.cs |
| Euler's Criterion | Medium | a^((M-1)/2) mod M | EulersCriterion.cs |
| Little Panda Power | Medium | Extended Euclid inverse | LittlePandaPower.cs |
| Primitive Problem | Medium | Order test over prime factors, φ(p - 1) | PrimitiveProblem.cs |
| Russian Peasant Exponentiation | Medium | Square-and-multiply on Gaussian integers | RussianPeasantExponentiation.cs |
| Time Complexity: Primality | Medium | Trial division to √n | Primality.cs |
| Sherlock and GCD | Easy | gcd of everything | SherlockAndGcd.cs |
| Sumar and the Floating Rocks | Easy | gcd(dx, dy) - 1 | SumarAndTheFloatingRocks.cs |
| The Chosen One | Medium | Prefix / suffix gcds | TheChosenOne.cs |
| Manasa loves Maths | Medium | Last three digits: multiples of 8 | ManasaLovesMaths.cs |
| Lucky Number Eight | Medium | Subsequence counts by remainder mod 8 | LuckyNumberEight.cs |
| Even Odd Query | Medium | Parity of the base, zero exponents | EvenOddQuery.cs |
| Number Groups | Easy | k³ | NumberGroups.cs |
| Jim and the Jokes | Medium | Day digits in base month, count pairs | JimAndTheJokes.cs |
| Salary Blues | Medium | gcd of differences | SalaryBlues.cs |
| Fibonacci GCD | Medium | gcd(F(a), F(b)) = F(gcd(a, b)) | FibonacciGcd.cs |
| Super Humble Matrix | Medium | Product of anti-diagonal factorials | SuperHumbleMatrix.cs |
| Vertical Sticks | Medium | Linearity of expectation | VerticalSticks.cs |
| Equations | Medium | Divisors of (n!)², Legendre's formula | Equations.cs |
| Megaprime Numbers | Medium | Generate prime-digit numbers, Miller–Rabin | MegaprimeNumbers.cs |
| Ajob Subsequence | Expert | Lucas's theorem | AjobSubsequence.cs |
| Baby Step, Giant Step | Easy | Case analysis, ⌈d / b⌉ | BabyStepGiantStep.cs |
| Little Ashish's Huge Donation | Easy | Binary search on the sum of squares | LittleAshish.cs |
| Wet Shark and 42 | Easy | Skip one even square in 21 | WetSharkAnd42.cs |
| Sherlock and Moving Tiles | Easy | Overlap side shrinks linearly | SherlockAndMovingTiles.cs |
| Count Solutions | Medium | Quadratic in y per x | CountSolutions.cs |
| Manasa and Sub-sequences | Medium | Running total and count | ManasaAndSubSequences.cs |
| Tara's Beautiful Permutations | Medium | Inclusion–exclusion over glued pairs | TarasBeautifulPermutations.cs |
| Game With Cells | Easy | ⌈n / 2⌉ · ⌈m / 2⌉, O(1) | GameWithCells.cs |
| Closest Number | Easy | Exact power, compare neighbouring multiples | ClosestNumber.cs |
| Help Mike | Medium | Residue counts in closed form, O(1) | HelpMike.cs |
| Sherlock and Probability | Medium | Prefix counts of '1's, reduced fraction | SherlockAndProbability.cs |
| Mehta and his Laziness | Medium | Count even square divisors from the factorisation | MehtaAndHisLaziness.cs |
| Binomial Coefficients | Hard | Lucas's theorem on base-p digits, BigInteger | BinomialCoefficients.cs |
| Sherlock and Pairs | Easy | Counting equal values, c·(c−1) ordered pairs | SherlockAndPairs.cs |
| GCD Product | Medium | Prime exponents ⌊n/p^k⌋·⌊m/p^k⌋ with a sieve | GcdProduct.cs |
| Die Hard 3 | Easy | Bézout: gcd divides c, and c fits a jug | DieHard3.cs |
| Picking Cards | Medium | Counting principle: product of (eligible − picked) | PickingCards.cs |
| Manasa and Factorials | Medium | Binary search on factors of five | ManasaAndFactorials.cs |
| Twins | Medium | Segmented sieve over the window | Twins.cs |
| Power of Large Numbers | Medium | Fermat: reduce the exponent mod p − 1 digit by digit | PowerOfLargeNumbers.cs |
| Smart Number | Easy | Odd divisor count means a perfect square | SmartNumber.cs |
| Sherlock and Counting | Medium | Parabola symmetry, binary search for the first K | SherlockAndCounting.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 |
| Move the Coins | Hard | Staircase Nim, Euler-tour XOR by depth parity | MoveTheCoins.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.