10,334 questions
6
votes
1
answer
276
views
Efficient algorithm to count contiguous subarrays that can form arithmetic progressions
I'm working on a problem where I need to count, for each possible common difference D, the number of contiguous subarrays whose elements can be rearranged to form an arithmetic progression with common ...
-3
votes
1
answer
164
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)
...
Best practices
0
votes
3
replies
58
views
Compare fingerprints with a set of 10*10^6 other audio fingerprints in postgres
So I have a function that I used to compare audio fingerprints with a few thousand audio fingerprints stored in a postgresql. What I did basically was:
def my_function(cur: Cursor, threshold: ...
-5
votes
1
answer
80
views
Asymptotic time complexity where a variable has a known upper bound?
Say I have an algorithm that runs in O(N*M + N + M). Say that although M can vary, it can only be between 1-20. For asymptotic complexity is M treated as a constant? Because you can't really take the ...
2
votes
3
answers
106
views
Big-O notation if n is a constant [duplicate]
Let's say I have this pseudocode:
int n = 100
for (int i = 1; i<=n; i++)
System.out.println("Hello!");
for (int j = 1; j<=n; j++)
System.out.println("World!!!");
end
...
0
votes
1
answer
67
views
Dotnet LINQ expressions time complexity
Considering elements as a list of objects (already loaded in memory, not a DB query) and given the following portion of code:
var filteresElements = elements.Where(el => el.Flag == true).Select(el....
2
votes
1
answer
302
views
Minimum cost to convert all 1's to 0's using window of size k
There is a row of toys, where each toy is represented as either:
1 → red toy (needs to be painted blue),
0 → blue toy (already painted).
An integer k is given. An operation can be performed as ...
-1
votes
4
answers
159
views
How can I optimize the time complexity of my brute-force solution for finding all unique triplets with sum zero?
I'm solving the "3Sum" problem where I need to find all unique triplets in an array that sum to zero.
Here’s my brute-force Java code:
public List<List<Integer>> threeSum(int[] ...
4
votes
2
answers
273
views
What is the time complexity of the following algorithm:
int k = 0;
for (int a = n; a >= 1; a /= 2)
for (int b = a; b >= 1; b--)
k++;
cout << k;
I would say that the answer is O(n), but the book where I have found the exercise says that ...
1
vote
2
answers
210
views
Big O for possibly non terminating algorithm
Suppose we want to generate a 5-digit unique student ID
i.e. there are N = 100,000 possible values (from 00000 to 99999).
What is the big O of the algorithm below?
- while True:
- Generate a random ...
4
votes
2
answers
132
views
Is it feasible to compute all simple paths between two nodes in a large directed graph (26,000 nodes, 86,000 edges)?
I have a large directed graph (not a DAG) with about 26,000 nodes and 86,000 edges. I want to find all possible simple paths (no repeated nodes) from one given node to another.
How difficult or ...
-3
votes
2
answers
92
views
Time Complexity Of A Recursive Function
I have a function of following form that I would like to know the time complexity of:
recursiveFunction(List<Input> list, int leftIndex, int rightIndex){
if(rightIndex <= leftIndex){
...
-4
votes
1
answer
83
views
What is the time complexity of this recursive function
I have a function of following form that I would like to know the time complexity of:
recursiveFunction(List<Input> list, int leftIndex, int rightIndex){
// If Terminating condition of ...
0
votes
1
answer
70
views
Couldn't understand on how lookup in a hashmap is O(N) while iterating over the same [duplicate]
I was doing leet code and came across https://leetcode.com/problems/two-sum/description/, which I've tried solving with a seen counter using hashmap. Below is the code:
class Solution:
def twoSum(...
-2
votes
1
answer
126
views
How to determine the complexity of a Turing machine from its state table?
I have an algorithm that is implemented by the following state table for a Turing machine:
𝑞1
𝑞2
𝑞3
0
0R 𝑞1
1L 𝑞3
0L 𝑞3
1
1R 𝑞1
0L 𝑞2
1L 𝑞3
_
_L 𝑞2
1S 𝑞0
_3 𝑞0
I want to determine the ...
0
votes
1
answer
108
views
Time complexity of dynamic programming
I'm looking at one of the solutions to the programming problem: Partition a Set into Two Subsets of Equal Sum. The programming problem: Given an array arr[], the task is to check if it can be ...
1
vote
1
answer
153
views
How to prove time complexity of an algorithm?
I'm trying to prove time complexity of merge sort algorithm in Isabelle HOL:
theory Merge_Sort_Time
imports Complex_Main "HOL-ex.BigO"
begin
fun merge :: "'a::linorder list ⇒ 'a list ...
4
votes
2
answers
187
views
What is time complexity of LINQ Order()/OrderBy() followed by Take(k)?
What is the time complexity of the following code in C#?
array.Order().Take(k).ToArray();
Will LINQ treat this as QuickSelect? Or, will it perform full array sorting with the complexity O(n log n)?
0
votes
1
answer
164
views
Java ArrayList and LinkedList performance [duplicate]
I know that it's a never-ending question that comes back every now and then, but I'm really confused about these two. This is what I understand about them.
In theory:
LinkedList is faster at adding ...
1
vote
1
answer
89
views
Can't tell the difference between two python n-queens solutions
Reading up on backtracking led me to a page on geeksforgeeks.org about solutions to the n-queens problem. The first solution is introduced as the "naive approach" that generates all possible ...
2
votes
3
answers
119
views
Exponential run time behavior in simple pyspark operation
My task is simple, i have a binary file that needs to be split into 8byte chunks where first 4bytes contain data (to be decoded in later step) the 2nd 4byte contain an int (time offset in ms).
Some of ...
2
votes
1
answer
166
views
Find number of valid squares from the provided number (>=4) of coordinates
I am trying to solve this question in O(N^3) time complexity but unable to get the right answer in C++. The question states: Design a function that takes in >=4 points and returns the number of ...
1
vote
1
answer
67
views
How do I calculate the time complexity of this problem?
I'm trying to determine the time complexity of the following code. It has a nested loop structure, and inside the inner loop, a recursive function is called. I want to understand how the recursive ...
2
votes
0
answers
37
views
What is the complexity of 2D array graph traversal? [duplicate]
Whether it is BFS or DFS, is it (MN)^(MN)? There're M*N nodes and, in the worst case, all the nodes have edges between each other.
7
votes
3
answers
448
views
Time limit exceeded on Leetcode 128 even for optimal time complexity
I was attempting LeetCode question 128. Longest Consecutive Sequence:
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an ...
2
votes
2
answers
127
views
Why is using a dictionary slower than sorting a list to generate frequency array?
I was doing this question on Codeforces (2057B - Gorilla and the Exam) where I had to use the frequencies of different numbers in a list. First I tried calculating it with a dictionary but I got TLE ...
-1
votes
1
answer
52
views
Array time complexity when modifying elements in Python
I was reading a bit on DS/A and found this cheat sheet on Leet Code..
Add or remove element from arbitrary index: O(n)
Access or modify element at arbitrary index: O(1)
Intuitively I would think they ...
0
votes
0
answers
71
views
How to Calculate Time Complexity Using Recurrence Tree for T(n) = T(n - sqrt(n)) + n^2
I'm trying to analyze the time complexity of the following recurrence relation using the recurrence tree method:
T(n) = T(n - sqrt(n)) + n^2
The challenge I'm facing is determining the height of the ...
6
votes
1
answer
115
views
What is the most efficient algorithm for merging sorted lists with a carry-forward mechanism for missing keys?
I'm working with multiple ordered lists, each containing tuples of the form (key, value), where each list is sorted in ascending order by key. I want to merge these lists into a single ordered list ...
1
vote
1
answer
107
views
Why can't two algorithms with the same time complexity pass the Kth Largest Element problem on LeetCode?
I am trying to solve the "Kth Largest Element in an Array" problem on LeetCode. I have two different approaches that both theoretically have the same time complexity (O(n) on average), but ...
0
votes
3
answers
148
views
How can i improve my python code of leetcode problem 345 and how i can i improve the time complexity [closed]
Task of the problem:
Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper
cases, more ...
0
votes
1
answer
64
views
Time complexity of summing m vectors of length n
I know this is a simple question, but I'm thrown off by some additions related to linear algebra problems being treated as constant time vs. linear time. In this case, I'm interested in summing m ...
3
votes
3
answers
195
views
How to count Basic Math Operations performed in a python recursive function
I need to write a python script that counts the number of times these operations: +, -, *, //, %, >, <, ==, <=, >= are performed in a piece of python code relative to the input of N.
...
-3
votes
1
answer
106
views
Why does Anagram have a time complexity of O(n+m) instead of O(n)
I was going through few leetcode problems and came across the Anagram Problem. The time complexity for the solution below was mentioned as O(n+m).
We are looking at the length of both strings which ...
0
votes
0
answers
45
views
Scalability Issue in recommender system
I'm new to recommender system and I'm currently building a collaborative filtering based recommender system. In my dataset there are current 600 users and 9000 items having different ratings. I have ...
2
votes
1
answer
120
views
Computing Big-O for multiple recursive calls where one is logn and the other is linear
def f(n):
if n <= 1:
return 1
return f(n-1) + f(n//2)
here n//2 is n divided by two truncated towards zero, so 3//2 is 1.
I've got this problem in my algorithms class. From my ...
0
votes
3
answers
110
views
Why does this haskell program have incorrect time complexity?
newtype Prob a = Prob { getProb :: [(a,Rational)] } deriving (Show,Eq,Functor)
flatten :: Prob (Prob a) -> Prob a
flatten (Prob xs) = Prob $ concat $ map multAll xs
where multAll (Prob innerxs,...
1
vote
1
answer
101
views
Maximum Path Sum Between Red Nodes in a Binary Tree
Problem Statement
I am trying to solve a variation of the Maximum Path Sum in a Binary Tree problem where some nodes in the tree are colored red. The path sum is only valid if:
The path starts and ...
-4
votes
2
answers
90
views
Why is there not much speedup when using parallel processing during bubble sort? [closed]
I want to compare the effect of multiprocessing for bubble sort.
Let us consider first the original one without multiprocessing:
import multiprocessing
import random
import time
import numpy as np
...
0
votes
0
answers
46
views
Time complexity of FEM-simulation of biphasic problem
I am trying to estimate the time complexity of an FEM simulation, that solves the normal contact between a biphasic block and an rigid indenter.
Say the block has a mesh with N x N x M nodes and the ...
1
vote
1
answer
128
views
consecutive pairs divisible by 3
The following problem was asked during an interview:
Given an array of integers as input, the size of an array is n.
Perform the below steps in a loop until the first n-1 items in the list are ...
7
votes
1
answer
130
views
Fastest way to find the smallest possible sum of the absolute differences of pairs within a single array?
By grouping all the items within an array into pairs and getting their absolute differences, what is the minimum sum of their absolute differences?
Example:
[4, 1, 2, 3] should return 2 because |1 - 2|...
3
votes
3
answers
434
views
Finding maximum groups in less time complexity
I have an array of size n, array[i] represents the count of items of a particular type, where i is in range 0 to n-1.
I want to pack the items in groups following below rules:
All items in a group ...
1
vote
1
answer
158
views
Given tasks and programmers solve the tasks in less time
I have a list of tasks of size n and the time taken to process is represented as tasks[i], where i is index for the task.
Processing Step: These tasks should be processed sequentially from i = 0 to i =...
7
votes
6
answers
448
views
How to move duplicates to the end of an array while preserving order in C?
I need to write a function in C that processes an array by moving all duplicate elements to the end of the array. The function should preserve the relative order of distinct elements, but the order of ...
-2
votes
1
answer
141
views
Why time complexity for Longest Increasing Path in a Matrix is O(nm)?
I am having a hard time understanding the time complexity for the solution to the following LeetCode problem 329. Longest Increasing Path in a Matrix:
Given an m x n integers matrix, return the ...
2
votes
2
answers
96
views
Deriving O(N*log(N)) for Comparison Sort, question on one particular step in wikipedia's derivation
I'm brushing up on my Big O notation via 'Cracking the Code Interview', 6th Ed., and in the chapter on Big O notation, he poses in example 8 that comparison sorts are generally O(n*log(n)).
I wished ...
2
votes
1
answer
158
views
Maximum the sum of lengths of two nondecreasing subsequence of given array
It is a famous question which asked about finding longest nondecreasing subsequence from a given array. The question is well studied and have O(n log n) time complexity solutions.
I have encountered a ...
2
votes
1
answer
109
views
Is My Time Complexity Analysis for Finding Universal Words O(m * k^2 + n*k) correct?
I’m given two string arrays, words1 and words2. A string b is a subset of string a if all characters in b appear in a with at least the same frequency. I need to find all strings in words1 that are ...
0
votes
1
answer
128
views
Does slicing in startswith and endswith make the time complexity O(n² * m) {where m is the average length of string in the list}, or is it O(n²)?
class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
n = len(words)
count = 0
for i in range(n):
for j in range(i+1, n):
...