Last active
September 14, 2020 13:30
-
-
Save kalyantm/3f3d67cbf645e7a66d5e12d68bd52487 to your computer and use it in GitHub Desktop.
DocType - Basics of GoLang
This file contains hidden or 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
// 1. Write a struct in Go for a Person object that has a numeric Age attribute. | |
type Person struct { | |
Age int | |
} | |
// 1.1) Write two functions in Go with the following function signature: func ([]Person) bool | |
// The first function should return true if there is a person who is exactly twice as old as any other person in the list, otherwise the function returns false. | |
func doubleAgeExists(persons []Person) bool { | |
// Approach: Use a set (made from a GoLang Map DS) to store the age details | |
// On one parse, check if age/2 or age*2 exists for the given age. | |
ageSet := make(map[int]bool) | |
for i := 0; i < len(persons); i++ { | |
if ageSet[persons[i].Age*2] || ageSet[persons[i].Age/2] { | |
return true | |
} else { | |
ageSet[persons[i].Age] = true | |
} | |
} | |
return false | |
} | |
// The second function should return true if there is a person who is at least twice as old as any other person in the list, otherwise the function returns false. | |
func atleastDoubleAgeExists(persons []Person) bool { | |
// Approach: Find the minimum and maximum aged persons in the struct | |
// Check if the eldest in the group is atleast twice the youngest | |
min := persons[0].Age | |
max := persons[1].Age | |
for i := 0; i < len(persons); i++ { | |
if persons[i].Age < min { | |
min = persons[i].Age | |
} | |
if persons[i].Age > max { | |
max = persons[i].Age | |
} | |
} | |
return (2 * min) <= max | |
} | |
// 1.2) Are you familiar with computational complexity? If so, what is the time complexity of the functions you implemented? | |
// Time complexity is basically the time taken by the program to complete its execution -> usually denoted in the big-O notation. | |
// Time complexity of both the functions implemented above is O(n), as we have one loop and we iterate through it once and perform | |
// some task in constant time. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment