JavaRush /Java Blog /Random EN /Java problems with a trick: Hello, interviews!

Java problems with a trick: Hello, interviews!

Published in the Random EN group
For JavaRush students , programming challenges, Java, and the validator are best friends. However, there comes a time for every developer Padawan when he needs to start going off the beaten track sometimes, come up with mini-projects for himself and prepare for interviews. At the interview, it would seem that you should encounter exactly the same practical Java problems as in the course. In most cases this is true, but some companies like to ask trick questions or something unusual. To avoid being confused during a stressful interview, it is useful to try solving such Java problems yourself, at home.
Java problems with a trick: Hello, interviews!  - 1
In this article we will look at half a dozen of these tricky tasks. We recommend that you first read the condition and try to solve it yourself. And one more thing: don’t forget to solve the Java problems from the course every day!

Java Problem - 1: Creating an infinite loop from scratch

Given a block of code. Complete it so that the loop becomes infinite.
class ToInfinity {
    public static void main(String[] args) {

//впишите code сюда

        for (int i = start; i <= start + 1; i++) {
             /* тут должен быть бесконечный цикл, менять ничего нельзя*/
        }
    }
}
“Nothing complicated,” you say. Most likely, you have found yourself in this situation more than once: while solving Java problems, you created an infinite loop and thought about how to get rid of it. It's the other way around. The trick is that the cycle itself and the conditions for exiting it cannot be changed. There are only two iterations. However, there are enough of them to create an infinite loop. It looks like it should only work for two iterations, but it can be made infinite by using overflow. Have you already guessed how?

Solution

Due to overflow. Integer.MAX_VALUEis the maximum value that intcan be stored in Java. If you reach Integer.MAX_VALUEand increment this value, you roll down to Integer.MIN_VALUE, that is, to the minimum value Integer. Thus, to solve this Java problem, we just need to assign a startvalue to the variable that is 1 less than the maximum value for the data type int. Task code in Java:
class ToInfinity {
    public static void main(String[] args) {
        int start = Integer.MAX_VALUE - 1;
        for (int i = start; i <= start + 1; i++) {
            //бесконечный цикл
            System.out.println(i); //убеждаемся в бесконечности цикла
        }
    }
}
What happens? We start with start=2147483645 (Integer.MAX_VALUE-1), at the next iteration the value becomes 2147483645, then 2147483646, then -2147483648, -2147483647... and so on.

Java task-2. Create a comment that will be executed

Well, here we are! From the very first lectures we heard that comments are not executed. That's why they are comments. We think that the solution to this problem is not always obvious for a Java programmer, even an experienced one. However, there is one tricky way to force the Java machine to “legally” run a comment for execution. Do you feel where the wind is blowing from? Try to guess!

Solution

Code for solving the problem in Java:
public class ExecutableComment {
    public static void main(String[] args) {
        // комментарий ниже будет выполнен!
        // \u000d System.out.println("выполняемый комментарий");
    }
}
If we type the code for this task in Java in the IDE, this is what we get:
выполняемый комментарий
The reason is that the Java compiler reads the Unicod character \u000das a new line, and reads our code as follows: The compiler deciphered code for solving the problem in Java:
public class ExecutableComment {
    public static void main(String[] args) {
        // the line below this gives an output
        // \u000d
        System.out.println("comment executed");
    }
}

Java Task - 3: Create a named loop

Another representative of the series “practical programming problems, Java in a spherical vacuum.” In the sense that it is not clear why this is necessary, it is unlikely that the cycle feels offended by the fact that it is impersonal. Well, okay, something else is important: the language allows you to give the cycle a name.

Solution

Note: to some, such “names” are known as “tags”, which are not recommended to be used in practice. Code for solving the problem in Java, demonstrating a named loop
public class NamedLoop {
    public static void main(String[] args) {
        loop1:
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                if (i == 3)
                    break loop1;
                System.out.println("i = " + i + " j = " + j);
            }
        }
    }
}
This is what the output will be if you run the program:
i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 0 j = 3
i = 0 j = 4
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 1 j = 3
i = 1 j = 4
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2
i = 2 j = 3
i = 2 j = 4
Here you can also use continue to go to the beginning of a named loop. And if necessary, you can use break(or continue) in a nested if-elsewith for-loop to break up several loops using if-else. This will help avoid setting a lot of flags and testing them if-elseto figure out whether to continue or exit the inner loop.

Java Problem - 4. About the only duplicate in an array of integers

Given an array (or ArrayList, as you prefer) of integers containing elements Integerfrom 1 to 100. This array has one and only one duplicated element. How to find it? Such tasks are more familiar to a Java programmer than the previous three. Because it is not about knowing the subtleties of language, which are almost never used, but about logic. The first unbridled impulse to solve by brute force disappears quite quickly when your head turns on or there is an attitude “I’m a programmer, I’m smart.” The only bad thing is that during an interview, under stress, this may not happen. So think now before you look into the solution!

The solution algorithm is as follows:

Calculate the sum of all numbers from 1 to 100. We think you know how to do this (for example, using the famous Gauss method). Now calculate the sum of the elements of your array or ArrayList’а. And... subtract the first amount from the second. Bingo! The resulting number is the value of the duplicate element. Java problem solution code for ArrayList.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class FindDuplicate {
    private static void findDuplicate(List<Integer> elements) {
//находим сумму всех уникальных элементов списка
        int distinctSum = elements.stream().distinct().mapToInt(e -> e).sum();
//находим сумму всех элементов списка
        int totalSum = elements.stream().mapToInt(e -> e).sum();
        System.out.println("Элемент, который повторяется : " + (totalSum - distinctSum));
    }

    public static void main(String[] args) {
//создаем список последовательных элементов на промежутке [1..101).
        List <Integer> elements = IntStream.range(1, 101).boxed().collect(Collectors.toList());
//устанавливаем элементу с индексом 53 meaning 23
        elements.set(53, 23);
        findDuplicate(elements);
    }
}
Another solution
import java.util.List;
import java.util.ArrayList;

public class Duplicate {

    public int findDuplicateNumber(List<Integer> numbers) {

        int highestNumber = numbers.size() - 1;
        int total = getSum(numbers);
        int duplicate = total - (highestNumber * (highestNumber + 1) / 2);
        return duplicate;
    }

    public int getSum(List<Integer> numbers) {

        int sum = 0;
        for (int num : numbers) {
            sum = sum + num;
        }
        return sum;
    }

    public static void main(String a[]) {
        List <Integer> numbers = new ArrayList <Integer>();
        for (int i = 1; i < 100; i++) {
            numbers.add(i);
        }
        //добавляем дубликат в список
        numbers.add(25);
        Duplicate dn = new Duplicate();
        System.out.println("Элемент, который повторяется: " + dn.findDuplicateNumber(numbers));
    }
}

Java Problem - 5. About a non-unique duplicate in an array of integers

If the previous problem seemed too easy to you, then try solving the following one: given a sheet of integers from 1 to 100. It contains duplicates (more than one). How to find elements that occur more than once (find the element itself and indicate how many times it occurs)?

Solution

The most logical solution here is to use a structure such as HashMap, since it stores data in key-value pairs. Code for solving the Java problem:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SomeDuplicates {
    private static void findDuplicates(List<Integer> elements) {
        HashMap <Integer, Integer > duplicates = new HashMap < >();
//заполняем Map duplicates значениями по принципу:
// ключ – meaning element, meaning – сколько раз он встречается
        elements.forEach(e -> duplicates.put(e, duplicates.get(e) == null ? 1 : duplicates.get(e) + 1));
//из duplicates убираем все элементы, которые встретorсь не более 1 раза,
//и сохраняем //результат в список (для удобства обработки на следующем шаге)
        List <Map.Entry <Integer, Integer> >
        result = duplicates.entrySet().stream().filter(d -> d.getValue() > 1).collect(Collectors.toList());
//выводим результат для всех элементов в списке result
        result.forEach(e -> System.out.println(String.format("Элемент %d  встречается %d раз", e.getKey(), e.getValue())));
    }

    public static void main(String[] args) {
        List <Integer> elements = IntStream.range(1, 101).boxed().collect(Collectors.toList());
        elements.set(97, 23);
        elements.set(27, 51);
        elements.set(99, 23);
        findDuplicates(elements);
    }
}

Conclusion

Practical Java problems are very different, and you don’t know what kind of unknown puzzle the interviewer will decide to give you. However, any adequate employer understands that much more important than the ability to solve tricky Java problems will be your ability to solve real practical problems , such as those that you will encounter during your work. So solve them as many as possible. This is why JavaRush was created. Materials from geeksforgeeks were used in preparing this article.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION