P#16 The last N elements

2020. 8. 21. 12:35PS/도전

All problems are from https://www.dailycodingproblem.com/

 

My Solution Codes : https://github.com/Kusin/DailyCoding

 

Kusin/DailyCoding

DailyCodingProblem. Contribute to Kusin/DailyCoding development by creating an account on GitHub.

github.com

Daily Coding Problem#16: The last N elements

Problem Description

 

Idea

My first approach is to use a List.

record orders to a list. inserting elements to the back takes constant time.

get_last(i) , List[-i] will do the job. Which will take contstant time too.

 

However, the last sentence of the task elarborates we have to be efficient in both time and space. How to be efficient in space? 

Since we need only the last maximum N values of the list, our minimum space complexity is O(N). 

So my idea is this -> Use deque.

 

deque is a data structure usually called as double-ended queue.

Insert/Deleting elements from front/back takes O(1) time. 

I knew this. However deque has another powerful feature.

Random Access takes O(1) time.

It implies that we can get the last ith element from the deque in O(1) time.

How does this work? One implemention to deque is partitioning constant-size arrays(possibly vectors). When insert, if it is needed, allocate a array and add it. (amortized O(1))

Since the size of arrays are constant, we can find the iterator of the nth element in constant time.

Check out this blog for details.

 

from collections import deque

dq = deque()

 

1. push back N-> dq.append(N)

2. pop back -> dq.pop()

3. push front N -> dq.appendleft(N)

4. pop front -> dq.popleft()

 

Implementation

728x90

'PS > 도전' 카테고리의 다른 글

Problem #18 Sliding Window  (0) 2020.08.23
P#17 Longest Path of a file system  (1) 2020.08.21
P#15 Random Element Selection  (0) 2020.08.19
P#14 Calculate Pi by Monte Carlo Method  (0) 2020.08.18
P#13 K-distinct Substring  (0) 2020.08.17