Loops

In a lot of problems, you don't need to know any special algorithms and techniques. What you need is just to use simple loops and variables. In this section, we will cover several common ways how you can solve problems with loops, and practice on several examples.

Largest and second-largest element

Finding the largest element in an array is extremely common. Here is how you can simply do it:

int[] a = {5, 7, 8, 9, -1, 3};
int maximum = a[0];
for (int i = 1; i < a.length; i++)
    if (a[i] > maximum)
        maximum = a[i];

What about the second maximum?

int[] a = {5, 7, 8, 9, -1, 3};
int firstMaximum = Math.max(a[0], a[1]);
int secondMaximum = Math.min(a[0], a[1]);

for (int i = 2; i < a.length; i++) {
    if (a[i] > firstMaximum) {
        secondMaximum = firstMaximum;
        firstMaximum = a[i];
    } else if (a[i] > secondMaximum) {
        secondMaximum = a[i];
    }
}

Now, can you find the third maximum? Try solving the following problem:

Hint
Solution

Converging pointers

Sometimes, it is very convenient to have two variables moving towards each other in a loop. For example, here is how you can check if the string is a palindrome:

boolean isPalindrome(String s) {
    if (s == null || s.length() == 0)
        return true;

    int l = 0, r = s.length() - 1;
    while (l < r) {
        if (s.charAt(l) != s.charAt(r))
            return false;
        l++; r--;
    }

    return true;
}

Take some time to understand this code, and after that, you can practice on the following problems:

#344 Solution
#125 Solution

Digits of the number

Another interesting technique is splitting an integer number into its digits. Here is for example how you can find the sum of the digits of a nonnegative number. Notice how in the loop we get the digits from the last to the first one:

int digitSum(int x) {
    int sum = 0;
    while (x > 0) {
        int lastDigit = x % 10;
        sum += lastDigit;
        x /= 10;
    }
    return sum;
}

You can practice this technique on the following problem:

Solution

More practice problems

Here are some more nice problems that don't require anything except loops and variables. Try to solve as many as you can!