쉐도잉 연습: Two Sum - Leetcode 1 - HashMap - Python - 영상으로 영어 말하기 배우기

레슨 만드는 중...
1
Let's solve leak code 1 to sum, the most popular leak code question.
2
So we're given an input array and some target, in this case 9.
3
And we want to find the two values in this input array that sum to 9.
4
So in this case, it's 2 and 7.
5
Now we want to return the indices of these two values.
6
So the index of 2 is 0, the index of 7 is 1.
7
So we return 0 and 1.
8
We're guaranteed that there's exactly one solution, so we don't have to worry about not finding a solution, and we don't have to worry about multiple solutions.
9
Now, the most intuitive way to solve this problem is basically just check every combination of two values
10
and see if they can sum up to our target.
11
So we start at two, we check every combination we can make that includes two.
12
So we scan through the remainder of the array, one, five, three, and check if any of those numbers added to two sums to our target four.
13
In this case, none of them do.
14
So next we can repeat the process.
15
Let's check every combination including one that sums up to target four.
16
So we scan through every element that comes after it, five and three, and we find that one added with three sums up to our target four.
17
Notice that we didn't have to check the values
18
that came before one because we already checked the combination two and one when we were up over here.
19
Remember when we checked every combination with 2.
20
So we didn't have to repeat that work down here.
21
We only had to check the numbers that came after 1.
22
So the runtime of this algorithm isn't super efficient.
23
This is basically brute force.
24
We're going through the entire array of length n and we're going to do that worst case n times for each number.
25
This means that overall worst case time complexity will be O of n squared.
26
So can we do better?
27
Now the thing to notice is that for each number,
28
for example, 1, the value we're looking for is the difference between the target and this value 1.
29
So we're looking for 4 minus 1, which is equal to 3.
30
So that means this is the only value we can add to 1 that'll equal the target.
31
So we don't have to check every number, we just want to know if 3 exists.
32
Now the easiest way we can do this, the most efficient, is by making a hash map of every value in our input array
33
so we can instantly check if the value 3 exists.
34
Now let's try the same problem except let's use a hash map this time.
35
Now in our hash map, we're going to be mapping each value to the index of each value.
36
So the index of 2 is 0, the index of 1 is 1, the index of 5 is 2, the index of 3 is 3.
37
So in our hash map, we're going to be mapping the value to the index.
38
now we could add every value in this array into the hash map before we start iterating through it
39
but there's actually an easier way to do it
40
if we added the entire array into the hash map initially
41
then we would get to the value 2 first right we
42
would want to check does the difference between target 4 minus this value 2
43
which is equal to 2 exists in our hash map and we would find that 2 does exist in our hash map, but we're not allowed to reuse the same one, right?
44
Because they're both at the same index.
45
We can't use the same value twice, so we would have to compare the index of our current
46
two with the index of the two that's in our hash map.
47
There's actually an easier way to do this though, and it's a little clever, and let me show you how to do it that way.
48
So doing it this clever way, initially we say our hash map is empty.
49
So we get to the value two first of all, right?
50
And we want to look for the difference 4 minus 2 in our hash map.
51
Our hash map is empty, so we don't find 2.
52
So then, after we've visited this element, then we can add it to our hash map.
53
So now that I'm done visiting it, I'm going to move to the second element 1.
54
And before I do that, I'm going to add this value 2 to our hash map, and the index of this value is going to be 0.
55
Now I'm at 1.
56
I'm looking for 4 minus 1, which is 3.
57
I see 3 isn't in our hash map, but it actually is in our array.
58
So what's the problem?
59
Well, for now, we're going to say we don't find a 3.
60
So we add 1 to our hash map.
61
The index of this 1 is 1.
62
And now we move to the next element, 5.
63
we check does 4 minus 5 uh it's 4 minus 5 exist in our hash map that's negative 1
64
so no it does not then we add this 5 to our hash map
65
and it's index which is 2
66
and we move to the last value in the array 3
67
we check does 4 minus 3 exist in our hash map now that's 1
68
so we see it does exist right over here.
69
The value exists and its index is one.
70
So now we found our two values that sum to the target and we want to return their indexes,
71
their indices, which are going to be one and three.
72
So with this algorithm, we don't have to initialize our hash map.
73
It can be initially empty and then we can just iterate through this array in one pass.
74
Now the reason the algorithm can work in that way with just one pass is this.
75
So let's say we had a giant array, right?
76
We know for sure that there are two elements in this array that sum to our target, right?
77
We don't know where they are.
78
They're at some arbitrary location.
79
When we visit the first one of those elements, our hash map is only gonna be this portion of the array.
80
It's only gonna have the values that came before the first value.
81
So we're going to notice that the second value
82
that can sum to the target is not going to be in our hash map yet.
83
But once we get to the second value, our hash map is going to be this portion.
84
So every value that comes before this, right?
85
So we're going to be guaranteed that once we visit the second element that sums up to the target, we're going to be guaranteed that the first one is already in our hash map.
86
So we're guaranteed to find the solution.
87
Now, since we only have to iterate through the array once, and we're adding each value to our hash map, which is a constant time operation,
88
and we're checking if a value exists in our hash map, which is also a constant time operation, the time complexity is going to be big O of n.
89
We are using extra memory, right?
90
That hash map isn't free, so the memory complexity is also going to be O of n
91
because we could potentially add every value to the hash map.
92
So now let's code the solution.
93
So remember we need a hash map, right?
94
I'm going to call this previous map because it's basically every element that comes before the current element.
95
Every previous element is going to be stored in this map.
96
We're going to be mapping the value to the index of that value.
97
So now let's iterate through every value in this array.
98
We need the index as well as the actual number.
99
So let's do it like this in Python.
100
Before we add this to our map, let's check if the difference, which is equal to target minus n.
101
Now let's check if this difference is already in the hash map.
102
if it is, then we can return the solution, which is going to be a pair of the indices.
103
So I can get the first index like this, and the second index is just i.
104
Now if we don't find the solution, then we have to update our hash map.
105
So for this value n, I'm going to say the index is i, and then we're going to continue.
106
Since we're guaranteed that a solution exists, we don't have to return anything out here, right?
107
But I'll just put a return for no reason.
108
Now let's see if it works. And it works perfectly.
109
So with this kind of neat little trick with just doing it in one pass, you can reduce the amount of code you have to write
110
and not have to worry about like edge cases and comparisons and things like that.

이 수업에 대하여

이번 수업에서는 Leetcode의 "Two Sum" 문제를 통해 다양한 가치를 조합하여 목표 합계를 찾는 알고리즘을 다룹니다. 이 문제는 배열 내에서 두 숫자의 인덱스를 찾아내는 과정을 포함하며, 배열의 다양한 조합을 확인하는 방법과 해시맵을 활용해 더 효율적으로 문제를 해결하는 방법을 배우게 됩니다. 이러한 과정을 통해 문제 해결 능력뿐만 아니라 영어 회화 연습에 필요한 기본적인 표현과 통계적 개념을 익힐 수 있습니다.

주요 어휘 및 구문

  • 배열 (array): 데이터를 정렬된 형태로 저장하는 구조.
  • 타겟 (target): 찾고자 하는 목표 숫자.
  • 인덱스 (index): 배열 내에서 각 요소의 위치.
  • 조합 (combination): 두 개 이상의 요소가 결합된 결과.
  • 해시맵 (hash map): 키-값 쌍으로 데이터를 저장하는 자료구조.
  • 효율성 (efficiency): 자원을 적게 투입하고 결과를 빠르게 얻는 능력.
  • 브루트 포스 (brute force): 문제 해결을 위해 가능한 모든 조합을 시도하는 비효율적인 방법.

연습 팁

이 비디오에서는 문제 해결 방법을 차근차근 설명하고 있습니다. 따라서 shadowspeaks 기법을 활용하여 반복적으로 따라 해보는 것이 좋습니다. 비디오의 속도는 적당하므로, 처음에는 천천히 따라하며 발음을 교정하고, 이후에는 속도를 높여 자연스럽게 여러 조합을 말해보세요. 또한, 알고리즘의 각 단계에서 설명되는 내용을 듣고 본인의 언어로 다시 정리해보면서 영어 발음 교정을 할 수 있습니다. 수업 내용이 명확하게 이해될 수 있도록 반복해서 연습하는 것이 중요하며, IELTS 스피킹처럼 과정을 자연스럽게 응용해 보세요. 이와 같은 방법으로 실력을 쌓아간다면, shadow speech 방식으로도 fluently와 정확하게 영어로 이야기하는 능력을 기를 수 있습니다.

쉐도잉이란? 영어 실력을 빠르게 키우는 과학적 방법

쉐도잉(Shadowing)은 원래 전문 통역사 훈련을 위해 개발된 언어 학습 기법으로, 다언어 학자인 Dr. Alexander Arguelles에 의해 대중화된 방법입니다. 핵심 원리는 간단하지만 매우 강력합니다: 원어민의 영어를 들으면서 1~2초의 짧은 지연으로 즉시 소리 내어 따라 말하는 것——마치 '그림자(shadow)'처럼 화자를 따라가는 것입니다. 문법 공부나 수동적인 청취와 달리, 쉐도잉은 뇌와 입 근육이 동시에 실시간으로 영어를 처리하고 재현하도록 훈련합니다. 연구에 따르면 이 방법은 발음 정확도, 억양, 리듬, 연음, 청취력, 말하기 유창성을 크게 향상시킵니다. IELTS 스피킹 준비와 자연스러운 영어 소통을 원하는 분들에게 특히 효과적입니다.