From b2e17abe77256fa9bd7bda3b6818475205d6e4e7 Mon Sep 17 00:00:00 2001 From: fahime Date: Wed, 15 Feb 2023 07:43:12 +0330 Subject: [PATCH] Add validate-subsequence.kt --- Easy/kotlin/validate-subsequence.kt | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Easy/kotlin/validate-subsequence.kt diff --git a/Easy/kotlin/validate-subsequence.kt b/Easy/kotlin/validate-subsequence.kt new file mode 100644 index 0000000..a050aee --- /dev/null +++ b/Easy/kotlin/validate-subsequence.kt @@ -0,0 +1,25 @@ +@file:JvmName("Main") +fun main() +{ + println("result is ${isValidSubsequence(intArrayOf(5,1,2,3,4),intArrayOf(1,2,3))}") +} + +// O(N) time and O(1) space +fun isValidSubsequence(array: IntArray, sequence: IntArray) : Boolean +{ + var i = 0 + var sequenceStarted = false + for(item in array) + { + if(item == sequence[i]) + { + sequenceStarted = true + i++ + + if(i == sequence.size) return true + + } else if (sequenceStarted) return false + } + + return sequenceStarted +} \ No newline at end of file