34,106 questions
-3
votes
1
answer
121
views
Monotonic Stack Algorithm: Is the Average Time Complexity θ(n) or O(n)? [closed]
The algorithm I've written for an assignment is closely related to this monotonic stack approach
https://www.geeksforgeeks.org/dsa/next-greater-element/
Best case:
n pushes → Time complexity: O(n)
...
Advice
1
vote
1
replies
34
views
Why do B-tree disk optimizations work when the OS controls physical disk layout?
I understand the standard explanation for why B-trees are used in databases: they minimize disk seeks by packing many keys into each node, keeping the tree shallow (3-4 levels), and enabling efficient ...
1
vote
1
answer
97
views
Sometimes wrong output in Java queue simulation
Problem summary:
Each person in line has tickets[i] tickets to buy. Every second
The person at the front buys one ticket.
If they still need more tickets, they move to the end of the queue.
We need ...
-2
votes
1
answer
33
views
Maximize Score based Prime Score Algorithm
Consider the following LeetCode problem:
You are given an array nums of n positive integers and an integer k. Initially, you start with a score of 1. You have to maximize your score by applying the ...
1
vote
1
answer
150
views
How can I update values in a nested JSON file using Python? [closed]
I have a JSON file with nested objects, and I want to update specific values inside it using Python.
The structure can vary, but it usually looks something like this:
{
"user": {
"...
-4
votes
1
answer
62
views
How to precompute nested date ranges efficiently to optimize range filtering and pagination? [closed]
📝 Body
I have a Mongo collection CollectionA where each top-level object contains a nested array of meetings now each meetings have start and end times, for example:
CollectionA = [
{
&...
-1
votes
1
answer
133
views
How can I merge two lists in Python while removing duplicates but preserving the original order? [duplicate]
I have two lists in Python:
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
I want to merge them into a single list such that:
No duplicates remain
The original order of elements is preserved
For the ...
1
vote
1
answer
43
views
Is circular linked list needed for "Circular" queue?/
I am learning about queue data structure in python. I learnt the implementation of a queue using list in python and the issue of memory wastage when we dequeue a few elements from the front. We use a ...
2
votes
2
answers
89
views
Mutual Friends using Graph Data Structure
I’m trying to implement a mutual friends feature using a graph data structure represented as an adjacency list in Python.
Each node represents a person, and each edge represents a friendship (an ...
1
vote
2
answers
95
views
Is there a bug in the method below (Data Structures & Algorithms by Robert Lafore)
The method below has been taken from the book Data Structures & Algorithms by Robert Lafore. This method is used to bubble sort a given array. nElems is the number of elements in the array. In my ...
1
vote
1
answer
34
views
Looking for a generic data structure being able to describe complex domain specific filters ( or standardized query language )
I'm searching for a very flexible data structure being able to describe what data to fetch from an API ( assuming I would own that API by creating a custom wrapper plugin ). The data itself is quite ...
3
votes
2
answers
474
views
Find employees with overlapping wortktime hours
Given StartTime and endTime for N employees, an employee can form a team if his working hour overlaps with other employees' (both startTime and endTime inclusive).
Find the maximum team size.
Example:
...
4
votes
2
answers
399
views
Number of lexicographical swaps to make the array non decreasing
A lexicographical swap is defined as:
At each step, pick the earliest possible inversion (i, j) (smallest i, then smallest j > i with a[i] > a[j]) and swap them.
Repeat until the array is sorted....
1
vote
1
answer
157
views
LeetCode 199. Binary Tree Right Side View constant memory complexity
I'm trying to solve LeetCode 199.
Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
I've ...
2
votes
1
answer
201
views
Subset data structure with O(1) insert, find, and delete_greater_equal
An abstract data type maintains a subset of numbers {0,1,2,...,n-1}. The operations allowed on this are:
insert(i) - Insert element i in the subset if not already present.
find(i) - Return True iff ...
10
votes
3
answers
611
views
Better way to search for a node in binary tree
This is the code I have written for searching a node in a tree as a part of my assignment:
typedef struct NODE
{
int key;
struct NODE *left, *right;
} Node;
Node *search(Node *head, int key)...
4
votes
2
answers
267
views
Answering Subarray H-index Queries Efficiently
I'm working on an interesting question about answering range h-index queries.
Fyi h-index is the max integer h that an author has published at least h papers that each are cited at least h times.
You ...
2
votes
1
answer
105
views
Saving embeddings from encoder efficiently with fast random access
I have embeddings (about 160 Million) that I created with a BERT-based encoder model.
Right now they are in a .pt format and takes about 500GB in the disk.
I want 2 things:
To save them in an ...
5
votes
1
answer
267
views
TypeCasting Math.pow(2,31) to int is not wrapping around as expected? [duplicate]
I was trying to check for wrap around property when the value is greater than the container that can hold it.
public class Main {
public static void main(String[] args) {
double value = ...
3
votes
2
answers
161
views
Mixed-type hash table design
I think this is a design problem. I’m trying to implement a hash table library in C89 in which the user will be able to insert mixed-type literal keys and values, e.g., HT_SET_LITERAL(&ht, "...
0
votes
0
answers
62
views
Database or data structure for fast exact counting
In databases such as PostgreSQL, doing exact counts like select count (*) from table where condition perform a full table scan.
PostgreSQL will need to scan either the entire table or the entirety
of ...
1
vote
1
answer
121
views
dynamically resizing array in queue implementation [closed]
I'm trying to write a queue that will store strings. Using GDB I can tell that I make a memory allocation error in the function resizeQueue.
Here's the exact message:
Program received signal SIGTRAP, ...
0
votes
0
answers
32
views
How to implement FIFO queue operations in DolphinDB similar to Python’s deque?
In Python, we can use collections.deque to implement FIFO queue operations. For example:
from collections import deque
queue = deque([1, 2, 3])
print("Initial queue:", queue) # ...
0
votes
1
answer
131
views
How to properly pass a data structure pointer from C++ to C#
I have a C++ dll that collects the data from our hardware. I am trying to get a pointer to that data from the C++ dll into C#. Here is the C++ data structure
#pragma pack (push, 1)
typedef struct ...
0
votes
0
answers
74
views
Non-bitwise move or `Move` trait? [duplicate]
In Rust, how can I define&manipulate objects that cannot be just copied bit-by-bit when they're moved?
For example, an object that contains a relative pointer (i.e. a pointer whose target is ...
4
votes
1
answer
81
views
A wait-free consensus algorithm for three processes, with a swap object and the fetch-and-increment object together in one atomic step
We know that a swap object consists of a shared register and supports a swap operation between the shared register and any local register, which atomically exchanges the values of the two registers.
A ...
0
votes
2
answers
250
views
RocksDB for efficient storage and retrieval of keys only (no values)
I have a use case requiring the reliable, durable storage, and efficient retrieval, of a large number of index entries (for which I've an application-specific serialization to bytes that preserves ...
3
votes
1
answer
92
views
Generating Recursive Data Structure From Table
I'm trying to convert this Wikipedia table into a nested JSON object.
I want to group each entry into its parent category. e.g.,
{
"name": "Mining, quarrying, and oil and gas ...
0
votes
0
answers
82
views
How to construct an AVL tree from a set of keys: 10, 20, 5, 4, 3, 2, 30, 40?
I'm trying to understand how an AVL tree is built from a sequence of integer keys. The keys I have are:
10, 20, 5, 4, 3, 2, 30, 40
I want to construct the AVL tree step by step and see how rotations ...
0
votes
1
answer
269
views
Contiguous type-agnostic pointer-data-structure implementation in C?
I am implementing search-trees and hash-tables in pure C (C89). Although the time+space asymptotic complexity is good, the constants and cache-efficiency… not so much.
The keys and values are void* ...
1
vote
2
answers
183
views
Does the type information of an object also take up space in memory?
I'm trying to understand how type information is stored in memory.
We often say that an 8-bit value can store 2⁸ = 256 different values. But I'm wondering — when we create an object of that type, ...
0
votes
1
answer
107
views
Is there a way to store Trie in chrome extension with a deeply nested root?
I'm trying to create a chrome extension where the user adds text snippets to the extension, then when they type in textarea/input/contenteditable/rich-text editors a selection dropdown appears with ...
0
votes
0
answers
119
views
Skip List with each column having an integer instead of copying objects
I tried my best implementing a Skip List in C++ in which I had a particular idea that I wanted to try out. Instead having every element in the base level be a column vector, I only only have a singly-...
2
votes
1
answer
78
views
Rotation of square Matrix not working correctly after first rotation
Please check the below code, the mat array after the second rotation should be identical to the target array tar. However, it is not happening. Could you please review to check where the logic is ...
2
votes
4
answers
185
views
How can I efficiently maintain median in a dynamic data stream with support for deletions?
I'm working on a problem where I need to maintain the median of a data stream, but unlike typical implementations that only support insertions, I also need to support deletions of arbitrary values.
...
0
votes
1
answer
61
views
Why Is My Leaderboard Showing Incorrect Ranks for Tied Scores(Python)?
I’m implementing a game leaderboard in Python where players can have the same score (ties), and I need to support three operations efficiently:
add_score player_id score — update a player’s score (...
-1
votes
1
answer
108
views
Kruskal's Algorithm Minimum Spanning Tree (Disjoint Set data structure)
I would like to generate a minimum spanning tree for the following graph:
I am using the disjoint set data structure and I am having trouble with the union (Union Rank) operation.
The edges get ...
1
vote
0
answers
53
views
plibsys data structures give incorrect results
I am trying to put together some code to find duplicated files between two or more directories, for this
I am using C libs like tinydir, and plibsys, the idea is traverse dirs get the hash of every ...
1
vote
3
answers
113
views
Is this doubly linked list function implemented correctly?
I was watching a youtube video on doubly linked lists in C. One of the functions made for the doubly linked list was an "insert_after_node" function, which as the name suggests inserts a new ...
0
votes
1
answer
52
views
Realtime Database structure creation fails – values disappear or produce errors
I'm attempting to manually create base data structures in the Realtime Database for a project called “Viral Content Platform.” The platform is being built to support campaign creation, sharing, and ...
0
votes
0
answers
27
views
Constrained Character List Type
Are there any commonly used implementations of a restricted string (or string-like) type that sets constraints on the range of characters allowed at different positions?
A simple example would be US ...
0
votes
1
answer
57
views
How should a list be pre-arranged in a tree, for bulk inclusion into an AVL tree?
I just asked this question, but for bulk-initialization of a red-black tree from a deduplicated sorted list. Now for an AVL tree it's easy for a layer with an odd number of elements; use the center ...
0
votes
2
answers
91
views
Can a red-black tree initialized by a list just make all its nodes Black?
If I have a list of values to insert into a new red-black tree, I could do an empty-tree initialization then do individual inserts. I wonder if I can take the list, sort it, then manually build the ...
1
vote
1
answer
96
views
Why does calling two functions in a single statement not affect the value? [duplicate]
In this code:
// Stack using LinkedList //
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL;
short isEmpty(void) {
...
1
vote
1
answer
197
views
How can I store ids in Python without paying the 28-byte-per-int price?
My Python code stores millions of ids in various data structures, in order to implement a classic algorithm. The run time is good, but the memory usage is awful.
These ids are ints. I assume that ...
0
votes
2
answers
208
views
How to build a nested adjacency list from an adjacency list and a hierarchy? [closed]
I have a simple adjacency list representation of a graph like this
{
1: [2, 3, 4],
2: [5],
3: [6, 9],
4: [3],
5: [3],
6: [7, 8],
7: [],
8: [],
9: []
}
which looks ...
2
votes
1
answer
101
views
shared red black tree among processes
I want to create a red-black tree that it is shared among different forked processes.
Linking to an old question of mine old_question there cannot be resizable data structures in the shared memory (...
1
vote
0
answers
92
views
How does Python represent slices in various cases?
Consider
l = [1, 2, 3, 4, 5]
print(l is l[:])
t = (1, 2, 3, 4, 5)
print(t is t[:])
print(t[1:] is t[1:])
print('aa'[1:] is 'aa'[1:])
print('aaa'[1:] is 'aaa'[1:])
The result is, somewhat surprisingly,...
-1
votes
1
answer
80
views
Ask for information about the Bubble sort algorithm [closed]
I have a question about the analysis of the bubble sort algorithm. I created the bubble sort algorithm in Python without including temporary storage. That means it directly swaps the adjacent pairs. ...
6
votes
1
answer
358
views
Optimizing LeetCode's "Minimum Pair Removal to Sort Array II" Solution to Prevent Time Limit Exceeded Errors
I am working on the LeetCode problem 3510. Minimum Pair Removal to Sort Array II:
Given an array nums, perform the following operation any number of times:
Select the adjacent pair with the minimum ...