Using the Two-Pointer Kotlin Approach to Solve for the Container with the Most Water

Written by okyrcheuskaya | Published 2023/01/31
Tech Story Tags: kotlin | leetcode | leetcode-practice | tutorial | coding | coding-skills | coding-challenge | kotlin-tutorial

TLDRThe problem is asking to find the maximum amount of water that can be stored in a container formed by two lines on a 2-dimensional plane and the x-axis. The two lines are represented by an integer array "height" where the ith element is the height of the line at the itH position. We then calculate the area between the two lines represented by the pointers using the formula.via the TL;DR App

This problem asks us to find the maximum amount of water that can be stored in a container formed by two lines, on a 2-dimensional plane and the x-axis. The container should not be slanted and the two lines are represented by an integer array "height" where the ith element is the height of the line at the ith position. The goal is to find the two lines that will form the container that stores the most water.

One way to solve this problem is by using a two-pointer approach. We initialize two pointers, one at the beginning of the array and one at the end of the array. We then calculate the area between the two lines represented by the pointers using the formula:

min(height[left], height[right]) * (right-left)

If this area is greater than the current maximum area, we update the maximum area.

We then move the pointer that is pointing to the shorter line towards the center, as it is the height of the shorter line that limits the amount of water that can be stored. We continue this process until the two pointers meet. This is because as we move the pointer pointing towards the shorter line towards the center, the width reduces. So, to get the maximum area we need to have a taller line.

Code:

fun maxArea(height: IntArray): Int {

   var left = 0

   var right = height.size - 1

   var amount = 0

   while (left < right) {

      val current = minOf(height\[left\], height\[right\]) \* (right - left)

      amount = maxOf(amount, current)

     if (height\[left\] < height\[right\]) {

            left++

          } else {

             right--

          }

         }
         return amount
         }

The time complexity of this approach is O(n), as we iterate through the array once using the two pointers. The space complexity is O(1), as we only use a few variables to keep track of the maximum area and the current pointers.

I hope this helps! Let me know if you have any other questions in the comments.


Written by okyrcheuskaya | Android developer
Published by HackerNoon on 2023/01/31