Created
January 12, 2022 18:40
-
-
Save parthdesai1208/e585d26e74bcc12567e2935153922501 to your computer and use it in GitHub Desktop.
Kotlin Code assessment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Three Sum | |
Have the function ThreeSum(arr) take the array of integers stored in arr, and determine if any three distinct numbers | |
(excluding the first element) in the array can sum up to the first element in the array. | |
For example: if arr is [8, 2, 1, 4, 10, 5, -1, -1] then there are actually three sets of triplets that sum to | |
the number 8: [2, 1, 5], [4, 5, -1] and [10, -1, -1]. | |
Your program should return the string true if 3 distinct elements sum to the first element, | |
otherwise your program should return the string false. The input array will always contain at least 4 elements. | |
Examples | |
Input: arrayOf(10, 2, 3, 1, 5, 3, 1, 4, -4, -3, -2) | |
Output: true | |
Input: arrayOf(12, 3, 1, -5, -4, 7) | |
Output: false | |
Solution:- | |
fun ThreeSum(nums: Array<Int>): Boolean { | |
if(nums.size < 4) return false | |
var counter = 0 | |
for (i in 0..(nums.size - 3)) { | |
for (j in (i + 1)..(nums.size - 3)) { | |
for (k in (j + 1)..(nums.size-1)) { | |
if (nums[i] + nums[j] + nums[k] == nums[0]) { | |
counter+=1 | |
if (counter == 3) { | |
return true | |
} | |
} | |
} | |
} | |
} | |
return false | |
} | |
fun main() { | |
println(ThreeSum(readLine())) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment