Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Daily Coding Problem: Problem #4
/*Good morning! Here's your coding interview problem for today. This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. You can modify the input array in-place.*/ using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { public static void Main(string[] args) { Console.WriteLine(Assert(GetLeastNonPresent(new List<int?>(){3, 4, -1, 1}), 2)); Console.WriteLine(Assert(GetLeastNonPresent(new List<int?>(){1, 2, 0}), 3)); Console.WriteLine(Assert(GetLeastNonPresent(new List<int?>(){}), 1)); Console.WriteLine(Assert(GetLeastNonPresent(new List<int?>(){1}), 2)); Console.WriteLine(Assert(GetLeastNonPresent(new List<int?>(){-1, -10}), 1)); Console.WriteLine(Assert(GetLeastNonPresent(new List<int?>(){0}), 1)); Console.WriteLine(Assert(GetLeastNonPresent(new List<int?>(){1, 2, 0, 2}), 3)); Console.WriteLine(Assert(GetLeastNonPresent(new List<int?>(){3, 4, -1, 1, 1, -1}), 2)); Console.WriteLine(Assert(GetLeastNonPresent(new List<int?>(){3, 4 }), 1)); } static int GetLeastNonPresent(List<int?> data) { if(!data.Any(f => f > 0)) { return 1; } int min = Int32.MaxValue; for(int i=0; i<data.Count; i++) { if(data[i] < 0) { data[i] = null; } else if(data[i] < min) { min = (int)data[i]; } } if(min > 1) { return 1; } for(int i=0; i<data.Count; i++) { if(data[i] != null) { data[i] = data[i] - min; } } //we want each element in the array be equal to its index //-1 indicates that there is such element at given index, null otherwise, first null will be our result for(int i=0; i<data.Count; i++) { int? current = data[i]; if(current != -1) { data[i] = null; } while(true) { if(current == null || current > data.Count - 1 || current == -1) { break; } int? tmp = data[(int)current]; data[(int)current] = -1; current = tmp; } } for(int i=0; i<data.Count; i++) { if(data[i] == null) { return i + min; } } return data.Count + min; } static bool Assert(int a, int b) { return a == b; } } }
run
|
edit
|
history
|
help
1
ss
Immutable
Bubble sort
Square Integer Matrix
BTC sell estimator
conter 1 in binnary number
24 101 251 Primes
งานสอบ
Interface IEnumerable
Only unique chars into string?