[Hash] Dictionary 시간복잡도 (2) - 시간초과 예시
2024. 5. 22. 04:10ㆍ개발의 흔적/코딩테스트
https://www.acmicpc.net/problem/2179
위 문제가 Hash 자료구조를 사용하지 않고 구현하면 시간초과가 나오기 쉬운 대표적인 문제라고 생각한다.

내가 처음 작성한 코드이다.
#time complexity: O(N) + O(N*(N-1)) = O(N^2) = 4억인뎀....
import sys
input = sys.stdin.readline
N = int(input())
words = {input().strip(): i for i in range(N)}
# print(words)
S_len = 0
S, T = "", ""
found = False
for nS in words.keys():
nS_len = len(nS)
if found is True and nS_len <= S_len:
continue
for nT in words.keys():
if nS in nT[:nS_len] and nS is not nT:
if nS_len > S_len:
S, T, S_len = nS, nT, nS_len
break
print(f"{S}\n{T}") if words[S]<words[T] else print(f"{T}\n{S}")
Big-O time complexity가 O(N^2) = 400,000,000 이라는 계산은 하였다만,
dictionary내에서 특정 String을 prefix로 가지고 있는 단어 찾는 방법이 딱히 떠오르지 않아서... '평균 시간 복잡도 안에 계산되서 문제없을수도?'라는 안일한 생각과 작성한 코드
왜 O(N^2)인가?
input List를 Dictionary에 넣을 때 O(N) +
이중 for문 : nS에 대한 for문 O(N) *
nT search하는 for문 O(N)
= O(N + N^2) = O(N^2)
즉 element의 빠른 탐색을 위해 dictionary structure를 이용하자!! 는 생각은 했지만,
( list(Array)는 한 element 찾는데에 iteration이 필수적이라 O(len(list)) 이지만, dictionary(Hashmap)는 O(1)이나까! )
결국 그 쓰임을 사용하지 못한 case...
'개발의 흔적 > 코딩테스트' 카테고리의 다른 글
| [완전탐색] 문제에서 '완전탐색일 수 밖에 없는 이유' 찾기 (0) | 2024.05.29 |
|---|---|
| [완전탐색] 중학교 수학으로 빠르게 코딩하기 (0) | 2024.05.28 |
| [heap][hash] heap과 hash 동시사용으로 시간복잡도 효율 높이 (0) | 2024.05.25 |
| [Heap] heapq의 시간복잡도(1) (0) | 2024.05.24 |
| [Hash] Dictionary의 시간복잡도 (0) | 2024.05.20 |