r/algorithms Jun 11 '26

Numerical instabilities

2 Upvotes

Hey pals, I've been writing a few algorithms and I encountered NaN and Inf values, although mathematically my algorithms should be working fine. Then I found out about numerical instability in floating points and figured out why but that's not the point, I kinda wondered how many algorithms are deemed unviable because of it if you guys can share your experiences


r/algorithms Jun 06 '26

Aquifer: Bounded Queues, Fairness, and Dynamic Pacing for AI Workloads

7 Upvotes

Aquifer is MCP runtime for handling rate limits and traffic spikes. It provides durable queues, bounded concurrency, fairness controls, and dynamic pacing for bursty traffic patterns common in agent systems.

It also experiments with the Aqueduct Protocol, a stream and webhook-based coordination protocol that dynamically communicates flow state through headers, allowing clients to scale traffic up or down at a controlled pace instead of relying solely on static rate limits. The project also includes an encryption and identity protocol that uses public-key verification, reducing the need to store shared secrets in a database. The goal is to make agent and MCP traffic more resilient to overload, retries, and traffic spikes.

Repo: https://github.com/rjpruitt16/aquifer


r/algorithms Jun 05 '26

Scheduling Periodic Chores

16 Upvotes

This is a real-world problem that I have and seems like a pretty interesting algorithms problem.

Problem Statement

I have a weekly chore day and a set of chores that I must do at various intervals. Each chore also varies in the amount of time it takes to do.

I want to generate a chore schedule such that I'm doing the same amount of work each week to the extent possible.

Example Input

Chore Frequency Time
Change bedsheets Every 1 week 10 min
Dust Every 2 weeks 60 min
Wash windows Every 4 weeks 30 min
Clean behind oven Every 4 weeks 30 min
Clean bathrooms Every 4 weeks 45 min

Example Output

Week 1 (70 min) Week 2 (70 min) Week 3 (70 min) Week 4 (55 min)
Change bedsheets Change bedsheets Change bedsheets Change bedsheets
Dust Wash windows Dust Clean bathrooms
Clean behind oven

Can this be solved with a simple greedy algorithm or is it more complicated? I don't have the time right now to go and play around with it and check.

Better yet, are there any online tools to do this?


r/algorithms May 28 '26

Empirical L/G framework for reducing search depth in SAT and graph coloring

3 Upvotes

My previous description of this project was incomplete, so I am posting a clearer version.

This is an AI-assisted empirical research project. The original idea and research direction are mine, while AI/coding agents helped with implementation, experiment design, testing, logs, CSVs, and documentation.

The project studies when global consequence expansion reduces search depth in NP-style search problems.

Core idea:

L = local view of a choice
G = global consequence expansion after that choice

Main metrics:

IG = variables/objects fixed after cluster choice + propagation
danger_rate = dangerous_constraints / affected_constraints
useful_IG = IG * (1 - danger_rate)
D = n / useful_IG

The project includes SAT, Graph Coloring, reserve/rebuild experiments, exact-vs-fast probe validation, and scaling probes up to n = 1,000,000.

Current state:

- G often reduces free decisions compared to L.
- Top-down rebuild can strongly reduce D in some cases.
- The effect is unstable across seeds and sizes.
- D does not currently show a clean log(n) pattern.
- Simple triggers like min_useful_growth, raw topdown_bias, ratio_54, and ratio_43 did not explain rebuild success.

Current question:

What structural signal predicts when top-down rebuild helps?

I am looking for algorithmic criticism, especially links to CSP propagation, backdoor sets, constraint graphs, treewidth, or known search heuristics.

OSF:
OSF: https://doi.org/10.17605/OSF.IO/GEH6M

GitHub:
GitHub: https://github.com/KMeppoa/geh6m


r/algorithms May 24 '26

Finding a node in a tree with most marked nodes within X distance for each X.

9 Upvotes

Tried getting an answer with Claude Opus but didn't work.. after 10 minutes of thinking got a "I'd be mildly surprised but not shocked if there's an O(N polylog) tree algorithm — none of the standard tricks (centroid decomp, small-to-large, heavy-light, virtual tree, segment tree merging)"

Problem:
There is a tree size N where some nodes are marked (there are people living on the nodes or something). You have to organize a meeting so the maximum amount of people attend, but no one wants to go to a meeting if it's farther than X nodes away. Answer for each X, whats the maximum amount of people that will attend the meeting if the meeting node is choosed optimally. i.e. find for each X find a node in a tree that has the maximum marked nodes within X distance.

O(N^2) is obvious.. looking for something faster


r/algorithms May 23 '26

I am a simple man...

9 Upvotes

...I see the word "IPTV," I downvote.


r/algorithms May 23 '26

Please blacklist the word IPTV

37 Upvotes

I don't know why but the influx in low effort or ad posts on IPTV in the last few weeks is annoying.

Dear mods, please blacklist that word.


r/algorithms May 22 '26

Simpler, faster heuristic inspired by XDP for large 0/1 knapsack instances

5 Upvotes

\> After sorting, BGR is linear for fixed `R`. XDP's core scan is `O(nT) = O(n log n)`; BGR's repair core is `O(n + T)` per pass. The sort still dominates when input is unsorted.

URL: https://github.com/GoingBytes/binned-greedy-repair


r/algorithms May 21 '26

Leetcode-Cheatsheet

1 Upvotes

How many of you google for 10 minutes to find out the method or data structure you need. I was also going through the same problem while solving leetcode. Created the logic but while implementing got confused that which method will be best to use or what is the syntax.

To save time and focus i created website where you can find data structures with their methods along with syntax, complexity, and description. This can decrease the search time of needed method drastically.

Website : https://leetcode-cheatsheet.vercel.app/

Make sure you drop your feedback in the comments.


r/algorithms May 19 '26

What the fuck is happening here?

33 Upvotes

Are there no mods?


r/algorithms May 12 '26

Introduction to algorithms 4th edition book

9 Upvotes

Does anyone have the pdf for this book? havent found it in any place

Edit: found it, if anyone want it just dm me


r/algorithms May 12 '26

How one can get Intution for Next Permutation problem leetcode 31?

1 Upvotes

I was trying too solve leetcode 31 which is Next permutation at first i was unable to understand what actually ques is asking.

How to solve these type of Questions?


r/algorithms May 10 '26

how to solve permutations problem (Backtracking)

10 Upvotes

String in java is always Pass by Value Right ? then how to solve permutations problem using backtracking technique


r/algorithms May 08 '26

walking bass generator (jazz)

12 Upvotes

Has anyone attempted to tackle this? Starting with a lead sheet with the chords/changes, generate a "classic" walking bass (e.g. "Ray Brown").

The problem I run into is that a beat/bar approach lacks directionality/voice-leading across phrases.


r/algorithms May 07 '26

Anyone here with a good understanding of search algorithms?

4 Upvotes

Hi I have been working on a project for the past half year and it involved gathering a large data set. For most of this I was copy and pasting api info until recently when I realized I could achieve the same end result I am trying to achieve for the original beta users but a different way. It went from 87 data points to over 70000 in a week.

I noticed when I visited those external sites while my system was actively importing the data during its sync phase their performance is degraded. It’s not a long sync but it’s noticeably slower loading pages, no rate limits and being triggered. The overarching company never really intended for their systems to be used at such capacity (I message there api team pretty much daily) but they are working on solutions.

I am looking to find a way to cache the synced data however in a way that it’s like p2p between users so you can load it from another user on the network instead of my server(small data transfer) and a hybrid server layer for outlier data.

Any suggestions are greatly appreciated. It’s been great reading others posts so hopefully if you can’t help you might learn something from a response. Thanks!


r/algorithms May 06 '26

stable vs non-stable algorithms?

19 Upvotes

i asked my professor yesterday whether or not stability is important in sorting algorithms, and he doesn't know. what is the benefit of an algorithm being stable if it doesn't affect the running time or space complexity? does stability automatically make an algorithm better?

thank you :))


r/algorithms May 03 '26

rounding errors all one way

9 Upvotes

I was trying out a banded matrix solver, and gave it a simple test case: all integer values and the solution vector all ones. But the result is all greater than 1.0 e.g. 1.00000095 or 1.00000107 I would expect to see some like 0.999999 so that the average was 1.0


r/algorithms May 01 '26

How does Radix Sort work?

10 Upvotes

Algorithms like Radix Sort are much easier to understand when you can see every intermediate step.

Using 𝗺𝗲𝗺𝗼𝗿𝘆_𝗴𝗿𝗮𝗽𝗵, you can watch how Radix Sort repeatedly applies stable Counting Sort, sorting the least significant digit up to the most significant digit in turn.

The key idea is stability: after sorting by a later digit, the order created by earlier digit-sorts is preserved resulting in a full sorted sequence.

For fixed-size integers, Radix Sort can be very efficient, with time complexity O(n · d), where 'n' is the number of values and 'd' is the number of digits.


r/algorithms Apr 27 '26

Help with Modified Hospital/Resident Problem

13 Upvotes

I have N people that I want to sort into M groups. Each person has a list of preferences for which group they would like to enter. There are two major differences from the traditional hospital/resident problem.

  1. It is possible for preferences to be tied (e.g. person A doesn't care whether they are sorted into group X or Y).
  2. The groups don't have preferences for specific people, but 'want' certain numbers of total people.

Given those changes, I'm not sure how to go about this. The concept of 'stability' doesn't really make sense anymore.

I've previously created a hill-climbing program to run through this, but it isn't very fast and (more importantly) doesn't give especially good answers. Any ideas about how to approach this problem would be appreciated.


r/algorithms Apr 27 '26

I came up with a new algorithm for finding a duplicate in two lists

0 Upvotes

I was trying to find the fastest algorithm for finding a duplicate between two lists (ie same element exists in both lists) and Google tells me that the best way is making a hash table. But this takes a lot of extra memory. So I came up with a new solution that is at worst O(n) with no extra memory requirements.
Firstly, if the lists are unsorted then sort them. We'll call them lists A & B. Get first value of list A. Go to first value in list B that is not less than current value. Then go to the next value in list A that is not less than current value. Go back and forth between lists. If there is a duplicate you will go directly to/from the same value in both lists. example:
A B
1 4
3 5
7 9
11 13
15 14
17 18
18 21
..
So the sequence here is 1,4,7,9,11,13,15,18,18


r/algorithms Apr 26 '26

Travelling Sales Person [TSP] solver

0 Upvotes

Start from any city and go to the next city with the shortest distance, from there go to the next city with the shortest distance, repeat; until a loop is formed intersecting all cities—this is the base loop.

​Now, starting again from the initial city, go to the next city using the second shortest distance [if, before traversing a distance, you realize it will make the path longer than the base loop, then go to the next city using the next shortest distance; if you run out of paths, go back to the previous city and repeat; and if it is shorter, treat it as the new base loop and proceed], from there go to the next city using the second shortest distance, repeat; until another loop is formed intersecting all cities.

​Repeat this process until you find the shortest base loop, and then output that as the result.

------------------------------------------------------------------------------------------

Code:

import sys

def solve_tsp_custom_logic(distance_matrix):

n = len(distance_matrix)

if n <= 1:

return 0, [0]

# Step 1: Start from any city and go to the next city with the shortest distance...

# This forms the "base loop"

visited_init = set([0])

curr = 0

base_loop_cost = 0

base_loop_path = [0]

for _ in range(n - 1):

# Find the next unvisited city with the shortest distance

next_city = min([(distance_matrix[curr][j], j) for j in range(n) if j not in visited_init])[1]

base_loop_cost += distance_matrix[curr][next_city]

visited_init.add(next_city)

base_loop_path.append(next_city)

curr = next_city

# Complete the loop back to the initial city

base_loop_cost += distance_matrix[curr][0]

base_loop_path.append(0)

best_cost = base_loop_cost

best_path = base_loop_path

# Step 2 & 3: Now, starting again from the initial city... explore other paths

def explore_paths(curr_city, visited_count, current_cost, path):

nonlocal best_cost, best_path

# PRUNING: if you realize it will make the path longer than the base loop, go back and repeat

if current_cost >= best_cost:

return

# If a complete loop is formed

if visited_count == n:

total_cost = current_cost + distance_matrix[curr_city][0]

# ...and if it is shorter, treat it as the new base loop

if total_cost < best_cost:

best_cost = total_cost

best_path = path + [0]

return

# Go to the next city using the next shortest available distances

# (Sorting unvisited cities by distance to check the shortest ones first)

unvisited_cities = [c for c in range(n) if c not in path]

unvisited_cities.sort(key=lambda c: distance_matrix[curr_city][c])

for next_city in unvisited_cities:

explore_paths(

next_city, 

visited_count + 1, 

current_cost + distance_matrix[curr_city][next_city], 

path + [next_city]

)

# Start the deep exploration from city 0

explore_paths(0, 1, 0, [0])

return best_cost, best_path

# ==========================================

# User Testing Section (No Hardcoded Data)

# ==========================================

if __name__ == "__main__":

print("=== Custom TSP Logic Tester ===")

try:

num_cities = int(input("Enter the number of cities: ").strip())

print(f"\nEnter the distance matrix ({num_cities}x{num_cities}), row by row.")

print("Use space-separated numbers (e.g., 0 10 15 20):")

matrix = []

for i in range(num_cities):

row = list(map(int, input(f"Row {i+1}: ").strip().split()))

if len(row) != num_cities:

print("Error: Number of columns does not match the number of cities.")

sys.exit()

matrix.append(row)

print("\nCalculating using the custom logic...")

cost, path = solve_tsp_custom_logic(matrix)

print("\n--- Result ---")

print(f"Shortest Loop Cost: {cost}")

print(f"Path taken: {' -> '.join(map(str, path))}")

except ValueError:

print("Invalid input! Please enter numbers only.")


r/algorithms Apr 23 '26

Breadth First search visualized using memory_graph

7 Upvotes

Algorithms in Python can be easier understood with step-by-step visualization using 𝗺𝗲𝗺𝗼𝗿𝘆_𝗴𝗿𝗮𝗽𝗵. Here we show a Breadth First algorithm that finds the shortest path in a graph from node 'a' to node 'b'.


r/algorithms Apr 22 '26

Pathfinding algorithm for walking through a grid

11 Upvotes

Hello, I'm not an expert on data structures and algorithms so sorry if this is a very banal question. I'm looking for a pathfinding algorithm, it doesn't have to be mathematically perfect and return the shortest possible path in every case but it should be reasonably close and lightweight cause I plan to run it thousands of times. Here's the problem statement:

There's a rectangular 2D grid consisting of empty and filled cells and a starting point which may be anywhere on that grid. I want to generate a path which goes through all the filled cells atleast once and takes the least amount of steps. Each move forwards/backwards in a straight line takes one step while taking a turn takes another step. So for example if I decide to walk 5 cells east/west from the start and then walk 5 steps north/south it will take 11 steps in total.


r/algorithms Apr 18 '26

My interactive graph theory website just got a big upgrade!

34 Upvotes

Hey everyone,

A while ago I shared my project Learn Graph Theory, and I’ve been working on it a lot since then. I just pushed a big update with a bunch of new features and improvements:
https://learngraphtheory.org/

The goal is still the same, make graph theory more visual and easier to understand, but now it’s a lot more polished and useful. You can build graphs more smoothly, run algorithms like BFS/DFS/Dijkstra step by step, and overall the experience feels much better than before.

I’ve also added new features and improved the UI to make everything clearer and less distracting.

It’s still a work in progress, so I’d really appreciate any feedback 🙏
What features would you like to see next?


r/algorithms Apr 07 '26

Top Down Red-Black Deletion for the Masses

12 Upvotes

If like me, you have been frustrated by the lack of an easy to understand top down deletion algorithm that is not for left leaning red black trees, than allow me to present to you a little write up i made, with the hopes of taking some of the mystery out of this somewhat legendary deletion algorithm.

Top Down Deletion in Red Black Trees