Top 10 Problematic Logical Interview Questions and Answers


Question 1: Reversing a String

Problem Statement: Write a function in GoLang to reverse a given string.

Solution:

package main

import "fmt"

func reverseString(str string) string {
    runes := []rune(str)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

func main() {
    input := "Hello, World!"
    output := reverseString(input)
    fmt.Println(output) // Output: !dlroW ,olleH
}

Explanation: In this example, we define a function reverseString that takes a string as input. We convert the string into a slice of runes and use two pointers, i and j, to swap the characters from the start and end of the slice until they meet in the middle. Finally, we convert the slice back into a string and return the reversed string.


Question 2: Finding the Missing Element

Problem Statement: Given two arrays where one is a shuffled version of the other, find the missing element.

Solution:

package main

import "fmt"

func findMissingElement(arr1, arr2 []int) int {
    missing := 0
    for _, num := range arr1 {
        missing ^= num
    }
    for _, num := range arr2 {
        missing ^= num
    }
    return missing
}

func main() {
    array1 := []int{1, 2, 3, 4, 5, 6, 7}
    array2 := []int{2, 3, 4, 6, 7, 1}
    missingElement := findMissingElement(array1, array2)
    fmt.Println(missingElement) // Output: 5
}

Explanation: In this example, we define a function findMissingElement that takes two integer arrays as input. We use the bitwise XOR operation to cancel out the elements that are common between the two arrays, leaving only the missing element.


Question 3: Checking Anagrams

Problem Statement: Write a function in GoLang to check if two strings are anagrams of each other.

Solution:

package main

import (
    "fmt"
    "sort"
    "strings"
)

func checkAnagrams(str1, str2 string) bool {
    if len(str1) != len(str2) {
        return false
    }
    str1 = sortString(str1)
    str2 = sortString(str2)
    return str1 == str2
}

func sortString(str string) string {
    runes := []rune(str)
    sort.Slice(runes, func(i, j int) bool {
        return runes[i] < runes[j]
    })
    return string(runes)
}

func main() {
    word1 := "listen"
    word2 := "silent"
    isAnagram := checkAnagrams(word1, word2)
    fmt.Println(isAnagram) // Output: true
}

Explanation: In this example, we define a function checkAnagrams that takes two strings as input. First, we check if the lengths of the strings are equal. Then, we sort the characters of both strings using the sort package’s Slice function. Finally, we compare the sorted strings to determine if they are anagrams.


Question 4: Generating Fibonacci Sequence

Problem Statement: Write a function in GoLang to generate the Fibonacci sequence up to a given number.

Solution:

package main

import "fmt"

func fibonacciSequence(n int) []int {
    sequence := []int{0, 1}
    for i := 2; i < n; i++ {
        sequence = append(sequence, sequence[i-1]+sequence[i-2])
    }
    return sequence
}

func main() {
    limit := 10
    fibSequence := fibonacciSequence(limit)
    fmt.Println(fibSequence) // Output: [0 1 1 2 3 5 8 13 21 34]
}

Explanation: In this example, we define a function fibonacciSequence that takes an integer n as input. We initialize the sequence with the first two Fibonacci numbers, 0 and 1. Then, we iterate from index 2 up to n, adding the sum of the previous two numbers to the sequence. Finally, we return the generated Fibonacci sequence.


Question 5: Finding the Longest Palindrome

Problem Statement: Write a function in GoLang to find the longest palindrome substring in a given string.

Solution:

package main

import "fmt"

func longestPalindrome(str string) string {
    if len(str) < 2 {
        return str
    }

    start, end := 0, 0

    for i := 0; i < len(str); i++ {
        len1 := expandFromCenter(str, i, i)
        len2 := expandFromCenter(str, i, i+1)

        maxLen := max(len1, len2)

        if maxLen > end-start {
            start = i - (maxLen-1)/2
            end = i + maxLen/2
        }
    }

    return str[start : end+1]
}

func expandFromCenter(str string, left, right int) int {
    for left >= 0 && right < len(str) && str[left] == str[right] {
        left--
        right++
    }

    return right - left - 1
}

Explanation: In this example, we define a function longestPalindrome that takes a string as input. We initialize two pointers, start and end, to keep track of the longest palindrome substring found so far. Then, we iterate through each character in the string and expand from the center to check for palindromes of odd and even length. Finally, we return the longest palindrome substring found.


Question 6: Finding Intersection of Two Arrays

Problem Statement: Write a function in GoLang to find the intersection of two integer arrays.

Solution:

package main

import "fmt"

func findIntersection(arr1, arr2 []int) []int {
    intersections := make(map[int]bool)
    for _, num := range arr1 {
        intersections[num] = true
    }
    result := []int{}
    for _, num := range arr2 {
        if intersections[num] {
            result = append(result, num)
            delete(intersections, num)
        }
    }
    return result
}

func main() {
    array1 := []int{1, 2, 3, 4, 5, 6, 7}
    array2 := []int{2, 3, 4, 8, 9, 10, 1}
    intersect := findIntersection(array1, array2)
    fmt.Println(intersect) // Output: [1 2 3 4]
}

Explanation: In this example, we define a function findIntersection that takes two integer arrays as input. We use a map to store the elements of the first array as keys. Then, we iterate through the second array and check if each element exists in the map. If found, we add it to the result array and remove it from the map to avoid duplicates. Finally, we return the intersection of the two arrays.


Question 7: Checking Balanced Parentheses

Problem Statement: Write a function in GoLang to check if a given string of parentheses is balanced.

Solution:

package main

import "fmt"

func isBalancedParentheses(str string) bool {
    stack := []rune{}
    opening := []rune{'(', '[', '{'}
    closing := []rune{')', ']', '}'}
    pairs := map[rune]rune{
        ')': '(',
        ']': '[',
        '}': '{',
    }

    for _, char := range str {
        if contains(opening, char) {
            stack = append(stack, char)
        } else if contains(closing, char) {
            if len(stack) == 0 || stack[len(stack)-1] != pairs[char] {
                return false
            }
            stack = stack[:len(stack)-1]
        }
    }

    return len(stack) == 0
}

func contains(slice []rune, char rune) bool {
    for _, c := range slice {
        if c == char {
            return true
        }
    }
    return false
}

func main() {
    input := "([]{()})"
    isBal := isBalancedParentheses(input)
    fmt.Println(isBal) // Output: true
}

Explanation: In this example, we define a function isBalancedParentheses that takes a string as input. We create an empty stack and define the opening and closing parentheses. Using a map, we associate each closing parenthesis with its corresponding opening parenthesis. Then, we iterate through each character in the string and perform the following actions:

  1. If the character is an opening parenthesis, we push it onto the stack.
  2. If the character is a closing parenthesis, we check if the stack is empty or if the top of the stack does not match the corresponding opening parenthesis. If either case is true, we return false.
  3. After processing all the characters, we check if the stack is empty. If it is, then the parentheses are balanced.

Question 8: Finding Prime Numbers

Problem Statement: Write a function in GoLang to find all prime numbers up to a given number.

Solution:

package main

import "fmt"

func findPrimes(n int) []int {
    primes := []int{}
    sieve := make([]bool, n+1)
    for i := 2; i <= n; i++ {
        if !sieve[i] {
            primes = append(primes, i)
            for j := i * i; j <= n; j += i {
                sieve[j] = true
            }
        }
    }
    return primes
}

func main() {
    limit := 30
    primeNumbers := findPrimes(limit)
    fmt.Println(primeNumbers) // Output: [2 3 5 7 11 13 17 19 23 29]
}

Explanation: In this example, we define a function findPrimes that takes an integer n as input. We initialize an empty slice to store the prime numbers found and create a sieve of size n+1 to mark non-prime numbers. Then, we iterate from 2 to n. For each number, if it is not marked as non-prime, we add it to the primes slice and mark all its multiples as non-prime in the sieve. Finally, we return the prime numbers found.


Question 9: Finding the GCD (Greatest Common Divisor)

Problem Statement: Write a function in GoLang to find the GCD (Greatest Common Divisor) of two integers.

Solution:

package main

import "fmt"

func findGCD(a, b int) int {
    for b != 0 {
        a, b = b, a%b
    }
    return a
}

func main() {
    num1 := 24
    num2 := 36
    gcd := findGCD(num1, num2)
    fmt.Println(gcd) // Output: 12
}

Explanation: In this example, we define a function findGCD that takes two integers a and b as input. We use the Euclidean algorithm to find the GCD. We repeatedly divide a by b and assign the remainder to a, and b to the previous value of a%b. We continue this process until b becomes 0, at which point a will be the GCD. Finally, we return the GCD.


Question 10: Sorting a Linked List

Problem Statement: Write a function in GoLang to sort a singly linked list in ascending order.

Solution:

package main

import "fmt"

type ListNode struct {
    Val  int
    Next *ListNode
}

func sortLinkedList(head *ListNode) *ListNode {
    if head == nil || head.Next == nil {
        return head
    }

    slow, fast := head, head

    for fast.Next != nil && fast.Next.Next != nil {
        slow = slow.Next
        fast = fast.Next.Next
    }

    middle := slow.Next
    slow.Next = nil

    left := sortLinkedList(head)
    right := sortLinkedList(middle)

    return merge(left, right)
}

func merge(left, right *ListNode) *ListNode {
    dummy := &ListNode{}
    curr := dummy

    for left != nil && right != nil {
        if left.Val < right.Val {
            curr.Next = left
            left = left.Next
        } else {
            curr.Next = right
            right = right.Next
        }
        curr = curr.Next
    }

    if left != nil {
        curr.Next = left
    }

    if right != nil {
        curr.Next = right
    }

    return dummy.Next
}

func main() {
    // Creating the linked list
    node1 := &ListNode{Val: 4}
    node2 := &ListNode{Val: 2}
    node3 := &ListNode{Val: 1}
    node4 := &ListNode{Val: 3}

    node1.Next = node2
    node2.Next = node3
    node3.Next = node4

    // Sorting the linked list
    sortedList := sortLinkedList(node1)

    // Printing the sorted list
    curr := sortedList
    for curr != nil {
        fmt.Println(curr.Val)
        curr = curr.Next
    }
}

Explanation: In this example, we define a function sortLinkedList that takes the head of a singly linked list as input. We use the merge sort algorithm to divide the list into two halves, sort them separately, and then merge them back in sorted order. We first find the middle element using the slow and fast pointer technique. We then recursively call sortLinkedList on the left and right halves, and merge the sorted halves using the merge function. Finally, we return the sorted linked list.


In conclusion, these top 10 problematic logical interview questions in GoLang cover a range of problem-solving skills and techniques. By understanding and practicing these solutions, you will enhance your problem-solving abilities and be prepared for challenging coding interviews.