๐Ÿ’ซ ETC/Leetcode

Week 2-1. [Hash Table] 242. Valid Anagram (Python3)

ming412 2023. 9. 1. 01:33

๋ฌธ์ œ ํ•ด๊ฒฐ ๊ณผ์ •

โœ๏ธ ๋‚˜๋งŒ์˜ ๋ฐฉ์‹์œผ๋กœ ๋ฌธ์ œ ์ •๋ฆฌํ•˜๊ธฐ (=์ฒด๊ณ„ํ™”)

https://leetcode.com/problems/valid-anagram/?envType=study-plan-v2&envId=top-interview-150 

 

Valid Anagram - LeetCode

Can you solve this real interview question? Valid Anagram - Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using

leetcode.com

s์™€ t ๋‘ ๊ฐœ์˜ ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์งˆ ๋•Œ, t๊ฐ€ s์˜ anagram์ด๋ผ๋ฉด True, ์•„๋‹ˆ๋ฉด False๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ผ.
  • | s, t | ∈ [1, 5*10^4]
  • ๋‘ ๋ฌธ์ž์—ด์˜ ์š”์†Œ์™€ ๋นˆ๋„์ˆ˜๊ฐ€ ์ •ํ™•ํžˆ ์ผ์น˜ํ•˜๋ฉด์„œ ์ˆœ์„œ๋งŒ ๋‹ค๋ฅด๋‹ค๋ฉด anagram์ด๋ผ๊ณ  ํ•œ๋‹ค.

 

๐Ÿ”Ž ์–ด๋–ค ์‹์œผ๋กœ ์ ‘๊ทผํ–ˆ๋Š”๊ฐ€?

์ด์ „ ๋ฌธ์ œ์—์„œ ํ™œ์šฉํ•œ Counter ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ–ˆ๋‹ค.

 

๐Ÿ™ˆ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ ํƒ: ์ž…๋ ฅ์˜ ํฌ๊ธฐ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ

Counter ํ•จ์ˆ˜๋Š” ๋‚ด๋ถ€์ ์œผ๋กœ linear search์ด๋‹ค.

 

๐Ÿ“ ์˜์‚ฌ ์ฝ”๋“œ

s์˜ ๋นˆ๋„์ˆ˜์™€ t์˜ ๋นˆ๋„์ˆ˜๊ฐ€ ๊ฐ™๋‹ค๋ฉด True๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

๐ŸŽฏ ๊ตฌํ˜„ ์ฝ”๋“œ

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return Counter(s) == Counter(t)

 

๋‚ด ์ฝ”๋“œ๋ฅผ ํƒ๊ตฌํ•ด๋ณด๊ธฐ

โฑ ์„ฑ๋Šฅ ์ธก์ • (์‹œ๊ฐ„๋ณต์žก๋„/๊ณต๊ฐ„๋ณต์žก๋„)

Counter ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ–ˆ์„ ๋•Œ ๊ฐ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋งŒํผ ๋ฌธ์ž๋ฅผ ์ˆœํšŒํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(n)์ด๋‹ค.

 

โœ๏ธ ์„ฑ๋Šฅ ํšŒ๊ณ 

1์ดˆ ์ œํ•œ์—์„œ O(n)์˜ ์ตœ๋Œ€ ์ž…๋ ฅ์€ 10^6์ด๋‹ค. ๋ฌธ์ œ์—์„œ๋Š” ์ตœ๋Œ€ ์ž…๋ ฅ์ด 5*10^4์ด๋ฏ€๋กœ ์„ฑ๋Šฅ์€ ๊ดœ์ฐฎ๋‹ค.

 

๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ์ฝ”๋“œ๋ฅผ ํƒ๊ตฌํ•ด๋ณด๊ธฐ

๐ŸŽฏ ๊ตฌํ˜„ ์ฝ”๋“œ

๋‘ ๋ฌธ์ž์—ด์„ ์ •๋ ฌํ–ˆ์„ ๋•Œ ์™„์ „ํžˆ ๋™์ผํ•˜๋‹ค๋ฉด, anagram์ด๋‹ค.

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return sorted(s) == sorted(t)

 

โฑ ์„ฑ๋Šฅ ์ธก์ • (์‹œ๊ฐ„๋ณต์žก๋„/๊ณต๊ฐ„๋ณต์žก๋„)

์ •๋ ฌ ์—ฐ์‚ฌ์˜ ์‹œ๊ฐ„๋ณต์žก๋„์— ์˜ํ•ด ๊ฒฐ์ •๋œ๋‹ค. ์ •๋ ฌ ์—ฐ์‚ฐ์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” ์ตœ์†Œ O(n log n)์ด๋‹ค.

 

๋А๋‚€ ์ 

๋ฐ”๋กœ ์ด์ „์— ํ’€์—ˆ๋˜ ๋ฌธ์ œ์—์„œ ์•Œ๊ฒŒ๋œ Counter ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

 

๋งŒ์•ฝ Counter ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์ง€ ์•Š์œผ๋ ค๋ฉด,

๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์ด์šฉํ•ด ๊ฐ ์•ŒํŒŒ๋ฒณ์˜ ๊ฐœ์ˆ˜๋ฅผ ์นด์šดํŠธํ•œ ๋’ค, ๋‘ ๋ฌธ์ž์—ด์ด ์ •ํ™•ํžˆ ์ผ์น˜ํ•˜๋Š”์ง€ ์—ฌ๋ถ€๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ์„ ๊ฒƒ์ด๋‹ค.