Questions tagged [data-structures]
A data structure is a way of organizing data in a fashion that allows particular properties of that data to be queried and/or updated efficiently.
data-structures
33,992
questions
-7
votes
0
answers
90
views
Please suggest me a code for this problem statement [closed]
Count the sequential key press
Count the sequence of key presses for characters in the given string by comparing it with the row-wise character (alphabet/digit) arrangements on a computer keyboard (...
0
votes
3
answers
50
views
Why using else if instead of if here when building a binary tree?
When building the insertion function in binary tree, I use two if statement to track the node( if the value is smaller than the current node,go left;if bigger,go right) .
I know the difference between ...
2
votes
1
answer
84
views
Finding repeating sequences with less than O(n^2) time complexity
Is it possible to find repeating sequences of any length (without complete overlaps) with a time complexity less than O(n^2) ?
For example, take a string like this:
...
-1
votes
1
answer
31
views
Linked Lists: AttributeError: 'int' object has no attribute 'next' [duplicate]
class ListNode:
def __init__(self, val=0, next=None) -> None:
self.val = val
self.next = next
def list_link(nums):
dummy = ListNode()
curr = dummy
for i in ...
0
votes
1
answer
53
views
Constructing Linked List in Rust from head to tail without unwrap
It is said that unwrap is unsafe and it should be avoided if possible.
While I was constructing a linked list, I found an unwrap inevitable.
My question is, is it possible to remove this unwrap or is ...
2
votes
0
answers
44
views
Most efficient way of determining if a subgraph of a graph is connected
Suppose I have a graph given by a Laplacian matrix $L$ corresponding to a regular discretization of $[0,1]^2$, meaning nodes $I={(i,j),\quad i,j=1,\dots,n}$ are connected with $(i+1,j),(i,j+1),(i-1,j),...
0
votes
0
answers
18
views
Time Complexity of my Subset Sum Problem's Solution [duplicate]
class Solution {
public:
vector<vector<int>> subsetsRec(int i,vector<int>& nums) {
vector<vector<int>> ans;
if(i==0){
vector<int>...
-3
votes
0
answers
25
views
Advice on ideal data structure for storing Long Jsons within SQLite/RDBMS
I am developing a project that displays a live rendering of bus, when the user clicks on a bus, i would like a linestring representing the bus route to appear/highlight.
I am currently attempting to ...
2
votes
3
answers
58
views
Why does this Linked List C function not work properly if previousNode->next is not set to NULL?
Node* deleteAtTail(Node* head)
{
if (head == NULL) /* If List is empty... */
{
return NULL;
}
else /* ...
-2
votes
0
answers
25
views
How to revise Leetcode problems [closed]
How do you guys revise questions like do you solve the question without looking or just go through the code or dry run or something else. For how much time shall I wait to revise a problem again.
If I ...
3
votes
0
answers
107
views
How do I pass a head-tail linked list to a function immutably?
If I need to pass a reference to an int immutably, I can pass it as a const int* to a function, as opposed to int*. This also helps the interface show that the pointed data won't be mutated.
Now I ...
-3
votes
2
answers
64
views
Add an ArrayList into a Queue (LinkedList) [closed]
As I know, we can make create a Queue using syntax along the lines of Queue<Integer> = new LinkedList<>().
But when I try to add the ArrayList<Integer> element into the Queue<...
1
vote
1
answer
94
views
Why does the sliding window algorithm not work for this problem statement?
The question is regarding an algorithm which I'm using to solve a problem. The problem statement is: (or view it here)
"Given arrival and departure times of all trains that reach a railway ...
-1
votes
0
answers
22
views
Is there any pattern for Graph in dsa [closed]
because there is no direct question in leetcode and i am confused on how to solve it
for example there is dfs and bfs way to traverse a graph, but how to apply that in problem solving questions?
I ...
1
vote
1
answer
38
views
Swift data structure reverse engineering
Given the following definition of ApiError:
struct ApiError: Error {
var statusCode: Int!
let errorCode: String
var message: String
init(statusCode: Int = 0, errorCode: String, ...
5
votes
1
answer
85
views
Minimal path on weighted tree query
Given a weighted tree with n vertices. there are q queries and for each query, you are given integers (u,k). find number of vertices v such that the smallest edge on the route from u to v is equal to ...
7
votes
2
answers
112
views
Do Python coders have a bias towards list over tuple? [closed]
Basic Facts
Lists are mutable (supporting inserts, appending etc.), Tuples are not
Tuples are more memory efficient, and faster to iterate over
So it would seem their use-cases are clear. ...
0
votes
1
answer
42
views
What does an "entry" refer to in a Hashmap? Does it mean the quantity of filled buckets, or the overall quantity of keys?
I am following along with The Odin Project.
They state "The product of these two numbers (load factor and current capacity) gives us a number, and we know it’s time to grow when there are more ...
0
votes
0
answers
19
views
Tensor of structs / multi-dimensional data structure of structs in mojo
I need a data strucuture that is a 2-dimensional array of lists of pairs. That is, if subdata = data[i][j], then subdata is a dynamic data structure that contains tuples of size 2.
My take on solving ...
2
votes
1
answer
77
views
Modified Dijkstra - Time Complexity?
I am solving the Leetcode Problem 787. Cheapest Flights Within K Stops.
Basically this is single source shortest path, but with max k steps allowed. So, we can't use normal Dijkstra algorithm, where ...
2
votes
2
answers
88
views
How to locate the most sparse point within a defined 2D region?
The core of the problem is to algorithmically determine the coordinates of the point E that maximizes the distance to the nearest other point in the bounded 2D space.
For example, in the space defined ...
3
votes
0
answers
82
views
Is there a pairing technique for round robin fairness among duplicate values in a pairing heap?
I am implementing a priority queue using a pairing heap. I have a working implementation that supports the following operations.
Push O(1).
Pop O(lgN).
Erase O(lgN).
Decrease Key o(lgN).
My priority ...
0
votes
1
answer
15
views
Issue solving 2-3 B-tree
I do not know how to delete the node 90 from this 2-3 B-tree
and i cant put in a simulator because i would need to replicate the tree exactly and I do not know how to do that. I would really ...
0
votes
0
answers
12
views
Data structure for rank and select of pattern on bit vector with constant query time
Looking through literature on advanced data structures and some implementations of balanced parenthesis representations I have stumbled upon proofs making use of rank and select operations on bit ...
0
votes
1
answer
54
views
Is there a name for this type of structured data, and what is a more efficient way to use it?
I'll try to make this question simple so that hopefully the concept is applicable to other fields.
I work with seismic datasets, where N earthquakes are recorded by M seismic stations. There is ...
3
votes
1
answer
111
views
Middle node of a linked list
i am trying to return a middle node of linked-list, it works well when number of nodes are even and when number of nodes are odd, segmentation fault is all i see. initially i return slow if fast ...
0
votes
2
answers
81
views
Unexpected behaviour with IEnumerable
In the code below I am mapping data that I got by paralelly downloading objects from AzureDevOps Rest Api. I noticed some weird bottlenecks in my code when transforming the mapDictionary to to an ...
1
vote
2
answers
65
views
How can I efficiently find the k-th node from the end and m-th node from the beginning of a singly linked list in one pass?
I'm working with a singly linked list in Java and need to implement a method that can simultaneously find the k-th node from the end and m-th node from the beginning of the list in a single traversal. ...
1
vote
2
answers
68
views
How can I efficiently reverse a k-group of nodes in a linked list in Java without using extra space?
I'm working on a problem where I need to reverse nodes in a singly linked list in groups of k. The solution needs to be in-place, meaning I can't use extra space beyond a few variables. I've tried ...
4
votes
1
answer
36
views
How to restructure instance segmentation predictions into a custom dictionary format in Python?
I'm performing instance segmentation using a model trained in RoboFlow, for the prediction result I'm getting:
[InstanceSegmentationInferenceResponse(visualization=None, frame_id=None, time=None, ...
0
votes
1
answer
57
views
Efficient Merge sort implementation in python
def merge(arr, l, m, r):
merged_arr = []
i, j = 0, 0
while (i < len(arr[l:m])) and (j < len(arr[m:r+1])):
if arr[l+i] < arr[m+j]:
merged_arr.append(arr[l+i])
...
1
vote
1
answer
71
views
How to store items in the LIFO stack in a cache-friendly manner?
EDIT / DISCLAIMER:
It appears that my understanding of cache lines was wrong which makes this question not relevant and misleading. I thought whenever CPU tries to fetch a memory at a specific index, ...
2
votes
3
answers
99
views
In C: Created a node, forgot return the pointer to the node, but code still runs as if I returned it
I was implementing some data structures for fun in C, and I was comparing the speed to other data structures I implemented. This one is a closed addressing hash table.
This is the code I used to ...
1
vote
2
answers
90
views
Calculating Postfix in c
I have been asked to calculate a postfix expression , which means that for every consequtive 2 numbers there is an arithmetical operation in between , for example fot the given string "123*+&...
0
votes
1
answer
73
views
Memory error when running multiset.erase(std::prev(multiset.end()));
#include <iostream>
#include <set>
#include <iterator>
using std::cout, std::endl;
using std::multiset;
int main() {
multiset<int> m;
m.insert(1);
m.insert(2);
...
1
vote
1
answer
44
views
Understanding Disk Reads and Cache Misses for B-tree and BST Queries
I am trying to understand how disk reads are handled when performing query operations on B-trees and have TWO questions.
I have the following B-tree structure:
[10, 20]
/ | ...
2
votes
1
answer
71
views
How to get the first value greater than x in a range with segment tree
I am trying to use a segment tree to handle queries (in O(log N) per query) of the form: find the first value > x in a particular range [ql, qr] (of an array of size N).
I've been using the ...
2
votes
2
answers
56
views
Attribute error : None type object in Linked List
I tried to create a simple single-linked list as the following:
class node:
def __init__(self, data=None):
self.data = data
self.next = None
class linkedlist:
def __init__(...
1
vote
0
answers
23
views
How to use METIS to partition directed graph with edge weights?
I have a directed graph which also havs multiple edges between same nodes.I want to partition the graph using the metis algorithm.
According to metis manual, metis can only generate partitions for ...
-3
votes
0
answers
45
views
I'm confused about how HashMap and HashSet manage Multiple Keys or Values [duplicate]
I have very low understanding in hashMap and hashSet internal functioning and i need help!
So:
HashMap:
I can't put two objects with same keys, So when i have object A and B, the first one has,
for ...
0
votes
1
answer
44
views
Spanning disjoint trees in directed bipartite graphs
Assume we have a directed bipartite graph G with two partitions, A and B. All the edges are assumed to start from A and end in B . Assume that every vertex has at least one adjacent edge. I want to ...
0
votes
1
answer
27
views
Red Black Tree Black Height Increase after Insertion
I understand that the black height of a RB tree increases after insertion when a red-red violation is propagated to the root, which then gets colored to red then recolored to black, and it causes for ...
0
votes
1
answer
65
views
Merge sort algorithm parallelization speed-up
I am doing a theoretical exercise for a class about a theoretical study of parallelizing the mergesort algorithm and the speed-up obtained for different amounts of cores.
I am using the following ...
1
vote
0
answers
41
views
Structuring Data for Bidirectional BLE Communication between MCU and Mobile App
I am currently sending data from STM32 to a mobile app using BLE. I use a specific characteristic for the data, which starts with a header containing a CMD. This CMD indicates the type of data being ...
3
votes
1
answer
107
views
How can I reduce the time complexity of the solution my subset optimization problem?
I have a list of tuples (a, b) of two unrelated positive integers. I am trying to create another list based off of this that maximizes the sum of a, while staying above a threshold.
I also have two ...
1
vote
1
answer
59
views
How to represent an algebraic expressions tree in a non-ambiguous way?
I have some physical model that needs to be represented as an algebraic expressions full binary tree. How can I represent such a tree in a non-ambiguous way?
Consider, as an example, the three full ...
1
vote
1
answer
64
views
Does a recursive segment tree require more space than an iterative one?
I'm learning the segment tree data structure.
I have seen several iterative segment trees that use only 2n space. So I tried to use the same build method in a segment tree with recursive update and ...
4
votes
2
answers
177
views
Count divisible elements in subarray
I am trying to solve the following exercise:
There is an array of positive integers with size N given 1 <= N <= 2*105. Each element of the array is at most 105 at all times.
After reading in ...
4
votes
0
answers
36
views
(Mutually) Recursive Pydantic models in Langchain
For context, I'm running python: 3.11.3, pydantic: 2.7.1, pydantic-core: 2.18.2
I am attempting to use Langchain with Pydantic JSON output parsing to make OpenAI api calls to prompt gpt4 and force the ...
0
votes
2
answers
23
views
Multiple City Codes in the Order File
I have an order file that has origin_city & destination_city fileds. Both are codes that reference records in the city file. I am trying to create a query that will select the city_name for both ...