Skip to content

About

421 HackerRank solutions in modern C# (.NET 10), each with xUnit tests from the problem's sample cases and CI on every push. Covers Warmup, Strings, Data Structures, Graphs, DP, Math, Game Theory and more.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

HackerRank Exercises in C#

build .NET C# Solutions Tests

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.

Highlights

  • 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

Project structure

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";
    }
}

Getting started

Requires the .NET 10 SDK.

git clone https://github.com/dejanciev-dev/hackerrank-exercises.git
cd hackerrank-exercises
dotnet test

To run the tests for one category or one problem:

dotnet test --filter "FullyQualifiedName~StringsTests"
dotnet test --filter "FullyQualifiedName~ClimbingTheLeaderboard"

Solutions

Warmup (10)

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

Implementation (67)

Problem Difficulty Approach Solution
Grading Students Easy Rounding rules GradingStudents.cs
Apple and Orange Easy Range check AppleAndOrange.cs
Number Line Jumps Easy Closed-form math, O(1) NumberLineJumps.cs
Between Two Sets Easy LCM / GCD BetweenTwoSets.cs
Breaking the Records Easy Running min / max BreakingTheRecords.cs
Subarray Division Easy Sliding window SubarrayDivision.cs
Divisible Sum Pairs Easy Remainder buckets, O(n + k) DivisibleSumPairs.cs
Migratory Birds Easy Frequency map MigratoryBirds.cs
Day of the Programmer Easy Julian / Gregorian calendars DayOfTheProgrammer.cs
Bill Division Easy Arithmetic BillDivision.cs
Sales by Match Easy HashSet pairing SalesByMatch.cs
Counting Valleys Easy Altitude tracking CountingValleys.cs
Electronics Shop Easy Sort + two pointers ElectronicsShop.cs
Cats and a Mouse Easy Distance comparison CatsAndAMouse.cs
Picking Numbers Easy Frequency of adjacent values PickingNumbers.cs
Climbing the Leaderboard Medium Dense ranking, single pointer O(n + m) ClimbingTheLeaderboard.cs
The Hurdle Race Easy Max TheHurdleRace.cs
Designer PDF Viewer Easy Lookup table DesignerPdfViewer.cs
Utopian Tree Easy Simulation UtopianTree.cs
Angry Professor Easy Counting AngryProfessor.cs
Beautiful Days at the Movies Easy Arithmetic digit reversal BeautifulDaysAtTheMovies.cs
Viral Advertising Easy Simulation ViralAdvertising.cs
Save the Prisoner! Easy Modular arithmetic, overflow-safe SaveThePrisoner.cs
Find Digits Easy Digit extraction FindDigits.cs
Append and Delete Easy Common prefix + parity AppendAndDelete.cs
Sherlock and Squares Easy Integer square root, O(1) SherlockAndSquares.cs
Repeated String Easy Math, no string building RepeatedString.cs
Jumping on the Clouds Easy Greedy JumpingOnTheClouds.cs
Equalize the Array Easy Most frequent value EqualizeTheArray.cs
Circular Array Rotation Easy Index arithmetic, no rotation CircularArrayRotation.cs
Sequence Equation Easy Inverse permutation SequenceEquation.cs
Jumping on the Clouds: Revisited Easy Circular simulation JumpingOnTheCloudsRevisited.cs
Cut the Sticks Easy Sort + distinct boundaries CutTheSticks.cs
Non-Divisible Subset Medium Remainder classes NonDivisibleSubset.cs
ACM ICPC Team Easy Pairwise bitwise OR AcmIcpcTeam.cs
Taum and B'day Easy Cheapest of buy vs. convert TaumAndBday.cs
Modified Kaprekar Numbers Easy Split the square ModifiedKaprekarNumbers.cs
Beautiful Triplets Easy Frequency product, O(n) BeautifulTriplets.cs
Minimum Distances Easy Last-seen index map MinimumDistances.cs
Halloween Sale Easy Simulation HalloweenSale.cs
Chocolate Feast Easy Wrapper exchange loop ChocolateFeast.cs
Service Lane Easy Range minimum ServiceLane.cs
Lisa's Workbook Easy Page simulation LisasWorkbook.cs
Flatland Space Stations Easy Gaps between sorted stations FlatlandSpaceStations.cs
Fair Rations Easy Greedy parity fix FairRations.cs
Cavity Map Easy Neighbor comparison CavityMap.cs
Manasa and Stones Easy Count the b-steps ManasaAndStones.cs
Happy Ladybugs Easy Case analysis + counting HappyLadybugs.cs
Strange Counter Easy Skip whole cycles, O(log t) StrangeCounter.cs
Library Fine Easy Date comparison LibraryFine.cs
Extra Long Factorials Medium BigInteger ExtraLongFactorials.cs
Bigger is Greater Medium Next permutation BiggerIsGreater.cs
Organizing Containers of Balls Medium Compare sorted row / column sums OrganizingContainers.cs
Encryption Medium Column-wise grid read Encryption.cs
Queen's Attack II Medium Nearest obstacle per direction, O(k) QueensAttackII.cs
Forming a Magic Square Medium Compare against all 8 magic squares FormingAMagicSquare.cs
Drawing Book Easy Turns from front vs. back DrawingBook.cs
3D Surface Area Medium Exposed faces per stack SurfaceArea3D.cs
Almost Sorted Medium Diff against sorted, try swap then reverse AlmostSorted.cs
Absolute Permutation Medium Blocks of size k AbsolutePermutation.cs
The Grid Search Medium 2D pattern matching TheGridSearch.cs
Larry's Array Medium Inversion parity LarrysArray.cs
The Time in Words Medium Pattern matching on minutes TheTimeInWords.cs
The Bomberman Game Medium Period-4 states, at most two detonations TheBombermanGame.cs
Ema's Supercomputer Medium Enumerate pluses, try every pair EmasSupercomputer.cs
Matrix Layer Rotation Hard Rotate each ring by r mod length MatrixLayerRotation.cs
New Year Chaos Medium Count overtakers in a 2-wide window NewYearChaos.cs

Strings (40)

Problem Difficulty Approach Solution
Super Reduced String Easy Stack, single pass SuperReducedString.cs
CamelCase Easy Count uppercase CamelCase.cs
Strong Password Easy Character classes StrongPassword.cs
Caesar Cipher Easy Modular rotation CaesarCipher.cs
Mars Exploration Easy Pattern comparison MarsExploration.cs
HackerRank in a String! Easy Subsequence matching HackerRankInAString.cs
Pangrams Easy HashSet Pangrams.cs
Weighted Uniform Strings Easy Run-length weights + HashSet WeightedUniformStrings.cs
Separate the Numbers Easy Try every first-number length SeparateTheNumbers.cs
Funny String Easy Two-direction diff FunnyString.cs
Gemstones Easy Set intersection Gemstones.cs
Alternating Characters Easy Adjacent comparison AlternatingCharacters.cs
Beautiful Binary String Easy Greedy scan BeautifulBinaryString.cs
The Love-Letter Mystery Easy Two pointers TheLoveLetterMystery.cs
Palindrome Index Easy Two pointers, O(n) PalindromeIndex.cs
Anagram Easy Letter counts Anagram.cs
Making Anagrams Easy Letter counts MakingAnagrams.cs
Game of Thrones - I Easy Odd-count parity GameOfThronesI.cs
Two Strings Easy Shared character TwoStrings.cs
String Construction Easy Distinct characters StringConstruction.cs
Two Characters Easy Try every letter pair TwoCharacters.cs
Sherlock and the Valid String Medium Frequency of frequencies SherlockAndTheValidString.cs
Sherlock and Anagrams Medium Substring signatures + C(n, 2) SherlockAndAnagrams.cs
Common Child Medium LCS dynamic programming, O(m) memory CommonChild.cs
Highest Value Palindrome Medium Two-pass greedy with change tracking HighestValuePalindrome.cs
Special String Again Medium Run-length encoding, O(n) SpecialStringAgain.cs
Bear and Steady Gene Medium Sliding window BearAndSteadyGene.cs
Maximum Palindromes Medium Prefix counts + modular inverse factorials MaximumPalindromes.cs
String Similarity Advanced Z-algorithm, O(n) StringSimilarity.cs
Morgan and a String Expert Suffix comparison with a sentinel MorganAndAString.cs
Short Palindrome Medium Counts of "x", "xy", "xyy" per letter pair ShortPalindrome.cs
Game of Thrones - II Advanced Multinomial of the half counts GameOfThronesII.cs
Determining DNA Health Hard Aho–Corasick + per-gene prefix sums DeterminingDnaHealth.cs
Two Two Advanced Trie of 2^0..2^800 TwoTwo.cs
Ashton and String Advanced Suffix array + LCP walk AshtonAndString.cs
String Function Calculation Advanced Largest rectangle on the LCP array StringFunctionCalculation.cs
Build a String Hard DP + Z-function for the longest copy BuildAString.cs
Circular Palindromes Advanced Manacher per rotation CircularPalindromes.cs
Find Strings Expert Generalised suffix array + prefix counts FindStrings.cs
Save Humanity Expert Z-function from both ends SaveHumanity.cs

Data Structures (68)

Problem Difficulty Approach Solution
Arrays - DS Easy Two-pointer reversal ArraysDS.cs
2D Array - DS Easy Grid scan HourglassSum.cs
Left Rotation Easy Index arithmetic LeftRotation.cs
Sparse Arrays Medium Frequency dictionary SparseArrays.cs
Balanced Brackets Medium Stack BalancedBrackets.cs
Dynamic Array Easy List of lists + XOR indexing DynamicArray.cs
Maximum Element Easy Stack of running maxima, O(1) ops MaximumElement.cs
Equal Stacks Easy Shrink the tallest EqualStacks.cs
Queue using Two Stacks Medium Lazy inbox / outbox, amortized O(1) QueueUsingTwoStacks.cs
Game of Two Stacks Medium Greedy + sliding exchange GameOfTwoStacks.cs
Largest Rectangle Medium Monotonic stack, O(n) LargestRectangle.cs
Simple Text Editor Medium Undo stack of inverse operations SimpleTextEditor.cs
Jesse and Cookies Easy Min-heap (PriorityQueue) JesseAndCookies.cs
QHEAP1 Easy SortedSet as a deletable heap Qheap1.cs
Truck Tour Medium Single pass with restart TruckTour.cs
Contacts Medium Trie with prefix counts Contacts.cs
Array Manipulation Hard Difference array, O(n + m) ArrayManipulation.cs
Reverse a Linked List Easy Pointer reversal ReverseLinkedList.cs
Merge Two Sorted Linked Lists Easy Dummy head splice MergeTwoSortedLists.cs
Insert a Node at a Specific Position Easy Walk to predecessor InsertNodeAtPosition.cs
Delete Duplicate-Value Nodes Easy Unlink adjacent duplicates DeleteDuplicateValueNodes.cs
Find Merge Point of Two Lists Easy Pointer switching, O(1) memory FindMergePoint.cs
Cycle Detection Medium Floyd's tortoise and hare CycleDetection.cs
Tree: Preorder Traversal Easy Recursive DFS TreeTraversals.cs
Tree: Inorder Traversal Easy Recursive DFS TreeTraversals.cs
Tree: Postorder Traversal Easy Recursive DFS TreeTraversals.cs
Tree: Height of a Binary Tree Easy Recursion TreeHeight.cs
Tree: Level Order Traversal Easy BFS with a queue LevelOrderTraversal.cs
Binary Search Tree: Insertion Medium Iterative descent BstInsertion.cs
Binary Search Tree: Lowest Common Ancestor Easy Split point, O(height) BstLowestCommonAncestor.cs
Is This a Binary Search Tree? Medium Ancestor bounds IsBinarySearchTree.cs
Get Node Value Easy Lead and trail pointers GetNodeValue.cs
Compare two linked lists Easy Walk in lockstep CompareTwoLinkedLists.cs
Delete a Node Easy Relink the predecessor DeleteNode.cs
Tree: Top View Easy Level order with column offsets TopView.cs
Swap Nodes [Algo] Medium Child arrays, iterative in-order SwapNodes.cs
Waiter Medium Stack simulation Waiter.cs
Down to Zero II Medium Forward DP over factor pairs DownToZeroII.cs
Castle on the Grid Medium BFS with sliding moves CastleOnTheGrid.cs
Poisonous Plants Hard Monotonic stack of death days PoisonousPlants.cs
AND xor OR Hard Simplifies to XOR; monotonic stack AndXorOr.cs
Find the Running Median Hard Two heaps FindTheRunningMedian.cs
Minimum Average Waiting Time Hard Shortest job first with a heap MinimumAverageWaitingTime.cs
No Prefix Set Hard Trie insertion NoPrefixSet.cs
Reverse a doubly linked list Easy Swap Next and Prev ReverseDoublyLinkedList.cs
Inserting a Node Into a Sorted Doubly Linked List Easy Find predecessor, relink both ways SortedInsertDoublyLinkedList.cs
Merging Communities Hard Union-find with sizes MergingCommunities.cs
Jim and the Skyscrapers Medium Decreasing stack of (height, count) JimAndTheSkyscrapers.cs
Queries with Fixed Length Hard Monotonic deque per query QueriesWithFixedLength.cs
Insert a Node at the Tail of a Linked List Easy Walk to the tail InsertNodeAtTail.cs
Insert a node at the head of a linked list Easy New head, O(1) InsertNodeAtHead.cs
Kundu and Tree Hard Black components + elementary symmetric sum KunduAndTree.cs
Median Updates Hard Two balanced sorted sets MedianUpdates.cs
Kindergarten Adventures Hard Circular difference array KindergartenAdventures.cs
Hash Tables: Ransom Note Easy Word counts RansomNote.cs
Frequency Queries Medium Value → count and count → values maps FrequencyQueries.cs
Friend Circle Queries Medium Union-find with sizes MaxCircle.cs
Min Max Riddle Medium Widest window per minimum MinMaxRiddle.cs
Mr. X and His Shots Hard Sorted endpoints + binary search MrXAndHisShots.cs
Subsequence Weighting Hard Fenwick tree of prefix maxima SubsequenceWeighting.cs
Super Maximum Cost Queries Hard Kruskal pair counts + binary search SuperMaximumCostQueries.cs
Direct Connections Hard Fenwick trees, cities by population DirectConnections.cs
Cube Summation Medium 3D Fenwick tree CubeSummation.cs
Tree: Huffman Decoding Medium Walk from the root, restart at leaves HuffmanDecoding.cs
Self Balancing Tree Medium AVL insertion with rotations SelfBalancingTree.cs
Find Maximum Index Product Medium Nearest larger on both sides FindMaximumIndexProduct.cs
Kth Ancestor Hard Binary lifting on a growing tree KthAncestor.cs
Array and simple queries Hard Implicit treap ArrayAndSimpleQueries.cs

Sorting (18)

Problem Difficulty Approach Solution
Big Sorting Easy Length, then ordinal compare BigSorting.cs
Mark and Toys Easy Sort + greedy MarkAndToys.cs
Find the Median Easy Sort FindTheMedian.cs
Closest Numbers Easy Sort + adjacent pairs ClosestNumbers.cs
Fraudulent Activity Notifications Medium Counting-sort sliding window FraudulentActivityNotifications.cs
Intro to Tutorial Challenges Easy Binary search IntroToTutorialChallenges.cs
Running Time of Algorithms Easy Count insertion-sort shifts RunningTimeOfAlgorithms.cs
Quicksort 1 - Partition Easy Stable three-way partition QuicksortPartition.cs
Counting Sort 1 Easy Frequency array CountingSort1.cs
Lily's Homework Medium Minimum swaps, both orders LilysHomework.cs
Insertion Sort - Part 1 Easy Shift right, print each step InsertionSort1.cs
Insertion Sort - Part 2 Easy Full insertion sort InsertionSort2.cs
Counting Sort 2 Easy Frequency array CountingSort2.cs
The Full Counting Sort Medium Stable buckets TheFullCountingSort.cs
Insertion Sort Advanced Analysis Advanced Inversions via merge sort InsertionSortAdvancedAnalysis.cs
Sorting: Bubble Sort Easy Count swaps BubbleSort.cs
Sorting: Comparator Medium Score desc, then name Comparator.cs
Minimum Swaps 2 Medium Cycle decomposition MinimumSwaps2.cs

Search (20)

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

Greedy (23)

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

Dynamic Programming (33)

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

Recursion (9)

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

Bit Manipulation (18)

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

Graph Theory (30)

Problem Difficulty Approach Solution
Breadth First Search: Shortest Reach Medium BFS BfsShortestReach.cs
Roads and Libraries Medium Union-find components RoadsAndLibraries.cs
Journey to the Moon Medium All pairs minus same-country pairs JourneyToTheMoon.cs
Even Tree Medium Count even subtrees EvenTree.cs
Components in a graph Medium Union-find sizes ComponentsInAGraph.cs
Snakes and Ladders: The Quickest Way Up Medium BFS over squares SnakesAndLadders.cs
Kruskal (MST): Really Special Subtree Medium Kruskal with union-find KruskalMst.cs
Prim's (MST): Special Subtree Medium Lazy Prim's with a heap PrimsMst.cs
Dijkstra: Shortest Reach 2 Hard Dijkstra with a binary heap DijkstraShortestReach.cs
Floyd : City of Blinding Lights Hard Floyd–Warshall FloydCityOfBlindingLights.cs
Jack goes to Rapture Medium Kruskal until 1 and n connect JackGoesToRapture.cs
Find the nearest clone Medium Multi-source BFS FindTheNearestClone.cs
Minimum Penalty Path Medium BFS over (node, OR) states MinimumPenaltyPath.cs
Matrix Hard Reverse Kruskal with machine flags MatrixMachines.cs
Rust & Murderer Hard BFS on the complement graph RustAndMurderer.cs
Roads in HackerLand Hard MST edge contributions, binary carry RoadsInHackerland.cs
Clique Medium Turán's theorem + binary search Clique.cs
Kingdom Connectivity Hard Relevant subgraph, Kahn's algorithm KingdomConnectivity.cs
Synchronous Shopping Medium Dijkstra over (node, fish mask) SynchronousShopping.cs
The Story of a Tree Medium Rerooting TheStoryOfATree.cs
Jeanie's Route Medium Prune to Steiner tree, 2·weight - diameter JeaniesRoute.cs
Beautiful Bead Ornaments Medium Generalised Cayley formula BeadOrnaments.cs
Real Estate Broker Hard Bipartite matching RealEstateBroker.cs
Problem solving Hard Path cover = n - matching ProblemSolving.cs
Demanding Money Hard Max-weight independent set, memoised branching DemandingMoney.cs
Liars Advanced Difference constraints, Bellman–Ford Liars.cs
Journey Scheduling Hard Diameter endpoints JourneyScheduling.cs
Computer Game Hard Bipartite matching on gcd > 1 ComputerGame.cs
Hacker Country Hard Karp's minimum mean cycle HackerCountry.cs
Far Vertices Medium Best centre vertex or edge FarVertices.cs

Mathematics (62)

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 Theory (23)

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

Adding a new solution

  1. Add a static class under the matching category folder in src/HackerRank.Solutions/, with a <summary> that describes the problem and links to it.
  2. Add tests with the problem's sample cases to the matching *Tests.cs file.
  3. Run dotnet test and add a row to the table above.

License

Solutions are my own work. Problem statements belong to HackerRank.

About

421 HackerRank solutions in modern C# (.NET 10), each with xUnit tests from the problem's sample cases and CI on every push. Covers Warmup, Strings, Data Structures, Graphs, DP, Math, Game Theory and more.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages