-2

I am stuck with an algorithm problem since days. If we have an array of numbers, lets say, arr[2,4,9] and a var k, lets say k=7.

Is there a common number possible which can be reached by adding k to each of the elements inside the arr[] ?

EDIT:


WHen i say common number i mean a number X=(nikarr[i]) where n is a positive integer which could be different for each i, k is a positive integer provided to us, arr is the array of numbers. So it is basically to find an n for which nikarr[i] = a common number for all i.


I had a hunch of using LCM concept here but was not able to figure out the algorithim all the way through. A lead will be highly appreciated.

2 Answers2

2

If you can add multiples of k to each element, then each element of the array can take on a value of the form

value := arr[i] + j * k

for some integer value j. Thus, they can only obtain the same value if all elements are initially some multiple of k difference from each other.

Alternatively, you can view this problem in terms of modular arithmetic. Only if all elements reduce to the same value modulo k will you be able to obtain a common value between them by adding multiples of k

forall e in arr ->  e mod k == c; for some constant c
Dillon Davis
  • 6,679
  • 2
  • 15
  • 37
  • That is too wary imo. OP asked a variable K and not its multiple. The Question is really absurd and needs more clarification. – Vishwa Ratna Jan 04 '19 at 05:11
  • If we interpreted OP's question literally, if would be equivalent to asking if for array `[a, b, c]`, are `[a + k, b + k, c + k]` equal. I feel that OP's mention of LCM is enough to clarify that we can add `k` multiple times to each element. – Dillon Davis Jan 04 '19 at 05:16
  • 1
    Yeah, LCM is just fine, Appreciate your response :) – Vishwa Ratna Jan 04 '19 at 05:18
  • @Dillin You are correct sir. We can indeed have multiples of k. Edits provided. – Adarsh Singh Jan 05 '19 at 14:34
0

Super easy.

    List<Integer> l = Arrays.asList(1, 6, 11);
    int k = 5;

    int min = l.stream().mapToInt(x -> x).min().getAsInt();
    boolean result = l.stream().mapToInt(x -> x)
            .map(x -> x - min)
            .allMatch(x -> x % k == 0);

    System.out.println("result = " + result);
talex
  • 17,973
  • 3
  • 29
  • 66