Skip to main content

Introduction to Two Pointers

· 3 min read
Mr. Frugal
I'm afraid of paying full price.

Let's explore the Two Pointers technique, its real-world applications, and the types of problems it can solve.

About the Pattern

The Two Pointers technique is a powerful approach used to efficiently traverse or manipulate sequential data structures like arrays or linked lists. As the name implies, it involves maintaining two pointers that move through the structure in a coordinated manner either starting from different positions or moving in opposite directions.

These pointers dynamically adjust based on specific conditions, enabling optimal solutions in terms of time and space complexity. Whenever a problem requires finding two elements in an array that satisfy a certain condition, the Two Pointers approach should be one of the first strategies to consider.

The pointers may traverse the data structure in one or both directions, depending on the problem. For example, to check if a string is a palindrome, one pointer can start at the beginning while the other starts at the end. At each step, their values are compared to verify the palindrome condition.

A naive approach to solving this problem would involve nested loops, resulting in a time complexity of O(n²). However, using Two Pointers moving toward the center from either end leverages the symmetry of palindromic strings. This allows for comparisons in a single loop, improving efficiency to O(n).

Examples

Below are some common problems that can be solved using this technique:

  • Reversing an array: Given an array of integers, reverse it in place.
  • Pair with a given sum in a sorted array: Given a sorted array, find a pair of numbers that sum to a target value T.

Does Your Problem Match This Pattern?

The Two Pointers technique is applicable if all the following conditions hold:

  1. Linear Data Structure: The input can be traversed sequentially, such as an array, linked list, or string.
  2. Processing Pairs: The problem requires processing elements at two different positions simultaneously.
  3. Dynamic Pointer Movement: The pointers move independently based on conditions. They may traverse the same data structure or two different ones.

Real-World Applications

Many real-world problems utilize the Two Pointers pattern. Here’s one example:

Memory Management

The Two Pointers technique plays a crucial role in memory allocation and deallocation. A memory pool typically has two pointers:

  • Start Pointer: Points to the beginning of the available memory block.
  • End Pointer: Indicates the end of the block.

When a process requests memory, the start pointer moves forward to allocate space. When memory is freed, the start pointer moves backward, marking the space as available. The end pointer remains fixed, preventing issues such as overlapping allocations.

Valid Palindrome Solution

Below are the steps to check if a string is a palindrome using the Two Pointers approach:

  1. Initialize two pointers—one at the beginning and one at the end of the string.
  2. Compare the characters at both pointers.
  3. If they do not match, return false. Otherwise, move both pointers one step toward the middle.
  4. Continue until the pointers meet.
  5. If no mismatch is found before they meet, return true.

프렌즈 시즌1 1화

· 7 min read
Mr. Frugal
I'm afraid of paying full price.

프렌즈 시즌1 1화 주요 표현

  • Finally, I figure. I'd better answer it. # 마침내 생각해보니, 그냥 전화를 받는게 낫겠다고 판단했어

  • I feel like someone grabbed my small intestine, pulled it out of my mouth. . . and tied it around my neck. 마치 누군가 내 작은창자를 잡아당겨 입 밖으로 끄집어낸 다음, 그걸 내 목에 감아 묶은 것 같은 기분이야. - 그는 (아내인 **캐롤(Carol)**이 떠나고(레즈비언이라는 사실을 깨닫고 이혼), 엄청나게 우울한 상태에서 이렇게 표현한 거죠)

  • No, don't! Stop cleansing my aura. - 그가 이혼 후 우울해하고 있을 때, **피비(Phoebe)**가 히피 스타일답게 **"네 오라를 정화해 줄게"**라며 손을 휘젓자, 로스가 짜증 내면서 이렇게 말한다

  • Fine. Be murky. # "알겠어, 그냥 우울한 채로 있어."

  • Why does everyone keep fixating on that? # "왜 다들 그거에만 집착하는 거야?"

  • Everybody, this is Rachel, another Lincoln High survivor. # "다들, 여기 레이첼이야. 링컨 고등학교를 함께 버텨낸 또 한 명의 생존자!"

  • You want to tell us now, or are we waiting for four wet bridesmaids? # "지금 얘기할래? 아니면 흠뻑 젖은 신부 들러리 넷을 기다릴까?"

  • I was more turned on by this gravy boat than by Barry. # "...배리보다 이 그레이비 보트에 더 끌렸어."

  • And then I really freaked out, when it hit me How much Barry looks like Mr. Potato Head. # 갑자기 **"배리가 미스터 포테이토 헤드처럼 생겼다"**는 생각이 들었고, 그제야 자신이 배리를 진짜로 사랑하지 않는다는 걸 깨닫게 된 거죠

  • I didn't know where to go, and I know you and I have drifted apart. . . # "어디로 가야 할지 몰랐어. 그리고 우리 예전처럼 가깝지 않다는 것도 알아..."

  • Who wasn't asked to the wedding. # "결혼식에 초대받지 못한 사람."

  • What if I want to be a purse? # "근데 내가 핸드백이 되고 싶으면?"

  • It's a metaphor, Daddy! # "그건 비유적인 표현이야, 아빠!"

  • I guess we've established she's staying with Monica. # "이제 확실해졌네, 레이첼은 모니카랑 지내기로 했다는 게."

  • Raindrops on roses And whiskers on kittens # 장미 위의 빗방울 그리고 아기 고양이의 수염

  • Doorbells and sleigh bells And something with mittens # 초인종과 썰매 종소리 그리고 장갑과 함께하는 무언가

  • Me and Chandler live across the hall. And he's away a lot. # 나랑 챈들러는 복도 건너편에 살아. 그리고 그는 자주 집을 비워.

  • Joey, stop hitting on her! # 조이, 그녀한테 작업 좀 그만 걸어!

  • He finally asked you out? It's a ''Dear Diary'' moment. # 그가 드디어 너한테 데이트 신청했어? 이건 완전 "일기장에 써야 할 순간" 이네!

  • -Go on! It's Paul, the wine guy! # 어서 가! 폴이잖아, 와인 가이!

  • Does he sell it, drink it, or he just complains a lot? # 그 사람 와인을 파는 거야, 마시는 거야, 아니면 그냥 불평만 하는 거야?

  • Rachel, what are you up to tonight? # 레이첼, 오늘 밤에 뭐 할 거야?

  • If you start with that, we're out of here. # 그 얘기 시작하면, 우리 바로 나간다.

  • She got the furniture, the stereo, the good TV. What did you get? You guys. You got screwed. # 그녀가 가구도 가져갔고, 스테레오도 가져갔고, 좋은 TV도 가져갔잖아. 그럼 넌 뭘 가졌는데? 너희들. 완전 당했네

  • I should've caught on when she went to the dentist four and five times a week. # 난 그녀가 일주일에 네다섯 번씩 치과에 갈 때 눈치챘어야 했어.

  • How did you get through it? # 넌 어떻게 이겨냈어?

  • I shredded my old boyfriend's favorite bath towel. # ...난 내 전 남자친구가 아끼던 목욕 수건을 갈기갈기 찢어버렸어.

  • Steer clear of you! # 너한텐 가까이 가지 말아야겠다!

  • You probably think it's about making love with your socks on, but it isn't. # 넌 아마 이게 양말 신고 사랑을 나누는 얘기라고 생각하겠지만, 그게 아니야.

  • Between us, we haven't had a relationship last longer than a Mento. # 우리 사이에, 사탕 하나 녹는 시간보다 오래간 연애가 없었잖아

  • Four years of closeness and sharing. After which, she ripped your heart out. . . # 4년 동안 함께하며 가까워지고, 모든 걸 나눴지. 그리고 나서... 그녀가 네 심장을 산산조각 냈지만.

  • You wanna spell it out with noodles? # 국수로 글자라도 만들어서 설명해줄까?

  • It's more of a fifth date kind of revelation. So there's going to be a fifth date? # 이건 좀 다섯 번째 데이트쯤 에 할 얘긴데. 그럼 다섯 번째 데이트가 있는 거네?

  • Being spit on is probably not what you need right now. # 지금 침 뱉는 거 가 네가 가장 필요했던 건 아닐 텐데.

  • I'm glad you smashed her watch. # 네가 그녀의 시계를 부숴버려서 다행이야.