LongestRepetition(new [] {1, 2, 1, 2, 1, 2, 3, 2, 1, 2})
should return new [] {1, 2, 1, 2}
.
Why? It should logically return
new [] {1, 2, 1, 2, 1, 2}
, because it's a longest repetition.
Check this generic linq solution:
public static T[] GetLongestRepetition<T>(T[] list)
{
return list.TakeWhile(o => list.GroupBy(x=>x)
.Where(grp=>grp.Count()>1)
.Any(grp=>grp.Key.Equals(o)))
.ToArray();
}
Usage:
int[] nums = new int[]{1, 2, 1, 2, 1, 2, 3, 2, 1, 2};
var result = GetLongestRepetition(nums);
Console.WriteLine("{0}", string.Join("", result));
string s = "aabaa";
var result1 = GetLongestRepetition(s.ToArray());
Console.WriteLine("{0}", string.Join("", result1));
string num = "1123811238479";
var result2 = GetLongestRepetition(num.ToArray());
Console.WriteLine("{0}", string.Join("", result2));
Note #1: This solution, unfortunatelly, uses a "hidden loop", see:
TakeWhile[
^]
Note #2: I haven't enough time to test my solution. So, it may need improvements...