It's O(n), since it must check every element. If you want better performance for max, you can use the heapq module. However, you have to negate each value, since heapq provides a min heap. Inserting an element into a heap is O(log n).

Answer from Matthew Flaschen on Stack Overflow
Discussions

How to Compute Max Value with Linear Time Complexity When 'k' Is Not Fixed?
This is also known as the range minimum query problem (or RMQ for short). You can split it by how long it takes to pre-process and how long it takes to answer a query. It looks like you want something that's O(n) pre-processing and O(1) query. There are a variety of approaches listed here: https://cp-algorithms.com/sequences/rmq.html I think the simplest one to understand that's linear time pre-processing and faster than O(log n) per query is this one: https://cp-algorithms.com/data_structures/disjoint_set_union.html#arpa . The optimal time complexity one is this: https://cp-algorithms.com/graph/lca_farachcoltonbender.html , but is much more complicated to implement. More on reddit.com
🌐 r/algorithms
6
10
January 28, 2024
What is the time complexity of the Python code below? Problem description and code provided. def max_independent_set(nums): #function dp=[0 for i in range(len(nums))] #create a dp table to find the max sum at index i
Example 1: Input: (7,2,5,8,6] Output: ... problem using dynamic Programming. Name your function max_independent_set(nums). Name your file MaxSet.py b. What is the time complexity of your implementation?... More on chegg.com
🌐 chegg.com
1
April 13, 2022
Is the min() function considered to be O(1) in python?
Yeah min() is O(n). But the problem's test cases are not strict enough to expose the inefficient algorithm. Python also adds another dimension because its builtin methods are often a lot faster than what you could write in pure python. I think that makes it easier to get away with a suboptimal algorithm. More on reddit.com
🌐 r/leetcode
3
1
May 2, 2023
python - Time complexity of min, max on sets - Stack Overflow
min, max have O(N) time complexity because they have to loop over the given list/string and check every index to find min/max. But I am wondering what would be the time complexity of min,max if use... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
wiki.python.org › moin › TimeComplexity
TimeComplexity - Python Wiki
[3] = For these operations, the worst case n is the maximum size the container ever achieved, rather than just the current size.
🌐
Medium
medium.com › @lcao_5526 › 3-ways-to-find-the-largest-number-in-python-and-their-complexities-49f2a1e221ee
3 Ways to Find the Largest Number in Python and Their Complexities | by Lulu Cao | Medium
April 13, 2024 - In conclusion, the best solution to find the largest number in Python will be using a max() function, which has a time complexity of O(n) and a space complexity of O(1).
🌐
Reddit
reddit.com › r/algorithms › how to compute max value with linear time complexity when 'k' is not fixed?
r/algorithms on Reddit: How to Compute Max Value with Linear Time Complexity When 'k' Is Not Fixed?
January 28, 2024 -

Body: Hello! I'm stuck on a problem and could really use some fresh perspectives. I'm trying to figure out a linear time solution (`Theta(n)`) for a problem that's a bit tricky due to its varying parameters.

Here's the Challenge: Picture a line of creatures, each with its own strength and a unique ability. We have two lists: `x` for their strengths and `k` for the number of creatures in front of each (including itself) they can turn to for help.

Example to Illustrate: Let's say `x = [5, 10, 7, 2, 20]` and `k = [1, 2, 1, 3, 2]`. We need to find the maximum strength each creature can muster. For the fourth creature, it looks at the 3 creatures (`k[3] = 3`) - itself and the two creatures before it, considers the strengths `[10, 7, 2]`, and realizes it can leverage a maximum strength of `10`.

Our goal is to output a list where each element is this maximum accessible strength for each creature.

Where I'm Stuck: Here's my Python attempt so far:

def calculate_ output(x, k):
    output = []
    for i in range(len(x)):
        start_index = max(0, i - k[i])
        end_index = i + 1
        output.append(max(x[start_index:end_index]))
    return output

This isn't efficient. The nested iterations due to `max` make it O(n^2). For each creature, we slice and dice through the list based on `k`, which isn't ideal.

Looking for Advice: I'm hitting a wall here. Maybe there's a way to do this with a sliding window, but the variable range in `k` throws a wrench in the works. Any thoughts on data structures or algorithms to make this linear?

Thanks in advance! Looking forward to your insights.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-maximum-record-value-key-in-dictionary
Python - Maximum record value key in dictionary - GeeksforGeeks
May 14, 2023 - The max() function is used to find the maximum value key, which has a time complexity of O(n log n) due to the use of a heap data structure.
🌐
Python Pool
pythonpool.com › home › blog › using python max function like a pro | python max()
Using Python Max Function Like a Pro | Python max() - Python Pool
June 14, 2021 - ... The time complexity of the python max function is O(n). Unlike max functions in other programming languages like C++, it offers a variety of uses. We can apply it on the string, which is not possible in other languages.
Find elsewhere
🌐
Medium
medium.com › @khasnobis.sanjit890 › design-an-algorithm-that-can-return-the-maximum-item-of-a-stack-in-o-1-running-time-complexity-b312b9575d9c
Design an algorithm that can return the Maximum item of a stack in O(1) running time complexity. We can use O(N) extra memory! : Stack Again : Chapter 3 : In Python | by Sanjit Khasnobis | Medium
April 26, 2022 - We will build the stack from scratch ... the Maximum element of the Stack. So we are allowed to use O(N) extra memory but we have to fetch the item in constant Time complexity of O(1). If you are reading this article for first time you can refer to my earlier article on Stack in python as below ...
🌐
Chegg
chegg.com › engineering › computer science › computer science questions and answers › what is the time complexity of the python code below? problem description and code provided. def max_independent_set(nums): #function dp=[0 for i in range(len(nums))] #create a dp table to find the max sum at index i
Solved What is the time complexity of the Python code | Chegg.com
April 13, 2022 - What is the time complexity of the Python code below? Problem description and code provided. def max_independent_set(nums): #function dp=[0 for i in range(len(nums))] #create a dp table to find the max sum at index i dp[0]=nums[0] #set first index with value of first element dp[1]=nums[1] #set first index with value of second element for i in range(2,len(nums)): #loop from second thrid index to last #store max of when either element is added to previous max or the max of the previous one or the element alone or the previous max alone dp[i]=max(nums[i],nums[i]+dp[i-2],dp[i-2],dp[i-1]) i=len(num
🌐
Quora
quora.com › What-is-the-best-algorithm-for-finding-the-max-in-an-array-and-what-is-its-complexity
What is the best algorithm for finding the max in an array and what is its complexity? - Quora
Answer (1 of 7): As it needs traversal of all of the array. Without checking all of the elements, min|max can't be find out. So worst case is O(n) Best is constant time
🌐
UCI
ics.uci.edu › ~pattis › ICS-33 › lectures › complexitypython.txt
Complexity of Python Operations
In fact, we could also simplify ... O(N Log N) - for fast Python sorting to just copy = sorted(alist) O(N Log N) - for fast Python sorting because sorted will create a list of all the values in its iterable argument, and return it after mutating (sorting) it. So we don't have to explicitly create such a copy in our code. This change will speed up the code, but it won't change the complexity analysis because O(N + N Log N) = O (N ...
🌐
Quora
quora.com › What-is-the-runtime-complexity-of-finding-the-maximum-value-in-an-array
What is the runtime complexity of finding the maximum value in an array? - Quora
Answer: Hello, Well, it will mainly depend on the content status of your array. If such content is sorted, you could have a complexity in O(1), since you just have to access to the last (or to the first, if item are sorted in inverted order) element. The access to that element will then, techn...
🌐
Unstop
unstop.com › home › blog › python max() function | all use cases with code examples
Python max() Function | All Use Cases With Code Examples
February 12, 2025 - Python max() function helps find the largest value among multiple objects or iterable items. Use the optional parameters key & default to customize its behavior.
🌐
GitHub
gist.github.com › yvan-sraka › 52384523a92bb0910d770f0fdde59bbd
Max function implementation explained in Python · GitHub
if list[0] > rec_max(list[1:]): # Calling here once return list[0] else: ''' Calling here again, which will lead to recurse the function it already computed the value for. This will impact the time complexity of the function majorly for large lists. ''' return rec_max(list[1:]) Instead of that, we can write it as below ·
🌐
GeeksforGeeks
geeksforgeeks.org › python › complexity-cheat-sheet-for-python-operations
Complexity Cheat Sheet for Python Operations - GeeksforGeeks
July 12, 2025 - This cheat sheet is designed to help developers understand the average and worst-case complexities of common operations for these data structures that help them write optimized and efficient code in Python. Python's list is an ordered, mutable sequence, often implemented as a dynamic array. Below are the time complexities for common list operations:
🌐
Reddit
reddit.com › r/learnpython › time-complexity of this algo?
r/learnpython on Reddit: Time-complexity of this algo?
May 22, 2019 -

I was taking a Hackerrank test for employment screening and some of the test cases kept coming back with a timeout error, meaning that the code is running too slow. However, it runs perfectly fine in Pycharm.

I think this is no more than O(n), or maybe O(3N), but what am I not understanding here?

Follow up, what can I do to make this run faster? I wasn't sure if the max() and count() functions were terribly inefficient, so I implemented my own on the spot that I knew were definitely O(n) and still got the error on some test cases. I also tried storing the list slice as a variable once per iteration so it wouldn't have to re-slice the array.

def frequencyOfMaxValue(price, query):

answers = []

for q in query:

maximum = max(price[q-1:])

c = price[q-1:].count(maximum)

answers.append(c)

return answers

Edit:

Here's the problem.

price is an int array as is query. Each element in the query array specifies a starting index(indexes start at 1, rather than 0 which is odd but anyway) of the price array in which to search for count of the maximum element. The count of occurrences of the maximum element of the subarray is added to the return array, answers.

It seems my issue was iterating through the subarray of price once to find the max, then a second time to count the occurrences of the max.

Top answer
1 of 5
3
First of all, iyou have a slight misunderstanding of big O notation. O(3N) is not a thing, it is O(N). Big O does not predict how fast your algo runs, it predicts how it scales with input size. O(N) is basically saying “it runs in linesr time.” O(3N) thus doesn’t make too much sense. If it is timing out, there is likely a O(logN) solution or something. Please post the actual problem abd format your code so we can help you better.
2 of 5
2
.count(x) means 'count all the objects in the sequence equal to x'. This is O(n) by definition, as the amount of items to process is always the length of the sequence. Meaning that if the sequence would be 10 times longer, it would need to count 10 times as many items. .max(sequence) means 'check all objects in the sequence and return the highest'. Also O(n) as there is no other option but to traverse the entire sequence, the same 10-fold example applies. Thus effectively doing both in a run is O(2n)*. This doesn't boil down to the 'efficiency' of each function, it's that both don't allow to be less or more efficient as they literally mean to check for something that needs all objects in a sequence to be checked, it's your combination that makes it inefficient. You then need to perform a custom method if you want to approach this in one iteration def count_max(seq): cur_max = seq[0] max_count = 1 for item in seq[1:]: if item > cur_max: cur_max = item max_count = 1 elif item == cur_max: max_count += 1 return max_count # then in your algo for q in query: answers.append(max_count(price[q-1:]) then another thing is to consider how exactly you are executing this for the price sequence. If you are repeating this for every object in price but just shifted one index (as query is like [1, 2, 3, 4 etc]) then you could also consider implementing this better instead of repeating the count_max step over and over again for a smaller slice of price. But I can only guess because you don't explain the background here. *: technically speaking O(2n) equals O(n) as O is in regard to complexity, not time duration.
🌐
AlgoCademy
algocademy.com › link
Time Complexity Practice 1 in Python | AlgoCademy
Learn "Time Complexity Practice 1 in Python" with our free interactive tutorial. Master this essential concept with step-by-step examples and practice exercises.