diff --git a/README.md b/README.md index f1c8cf3..5eb4cd0 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,8 @@ For a glimpse into my journey and the projects I've been involved in, feel free - Finding Most Frequent Elements in an Array - Building a Product Array without the Element Itself - Checking Validity of a Sudoku Grid - - Encoding and Decoding Functions for Strings + - Encoding and Decoding Functions for Strings + - Finding the Longest Consecutive Sequence in an Array ## Technologies Used - [Hugo Static Site Generator](https://gohugo.io/) diff --git a/config.yml b/config.yml index 5a0124e..b488df2 100644 --- a/config.yml +++ b/config.yml @@ -111,7 +111,7 @@ params: - name: ycombinator url: "https://news.ycombinator.com/user?id=bovem" - name: linkedin - url: "http://www.linkedin.com/in/avnish-pal" + url: "https://www.linkedin.com/in/avnish-pal" # - name: stackoverflow # url: "https://stackoverflow.com/users/15039093/avnish-pal" - name: rss diff --git a/content/contents.md b/content/contents.md index 5bc7be5..99bedea 100644 --- a/content/contents.md +++ b/content/contents.md @@ -37,3 +37,4 @@ summary: "Index of all content" - Building a Product Array without the Element Itself - Checking Validity of a Sudoku Grid - Encoding and Decoding Functions for Strings + - Finding the Longest Consecutive Sequence in an Array diff --git a/content/posts/dsa/longest-consecutive/index.md b/content/posts/dsa/longest-consecutive/index.md new file mode 100644 index 0000000..2b660ac --- /dev/null +++ b/content/posts/dsa/longest-consecutive/index.md @@ -0,0 +1,269 @@ +--- +author: "Avnish" +title: "Finding the Longest Consecutive Sequence in an Array" +date: "2023-11-09" +description: "Implement a longestConsecutive function that returns the length of the longest sequence of consecutive numbers in an array" +tags: ["data-structures", "arrays", "hashmaps", "go", "neetcode-150", "leetcode-medium"] +categories: ["Data Structures"] +series: ["Data Structures and Algorithms"] +aliases: + ["finding-the-longest-consecutive-sequence-in-an-arrray", "longest-consecutive"] +ShowToc: true +TocOpen: false +comments: false +cover: + image: "longest-consecutive-cover.png" + linkFullImages: true + alt: "The longestConsecutive function will return the length of the longest sequence if consecutive numbers in the input array" + caption: "" + relative: false + responsiveImages: false +math: true +--- + +# Problem Statement +We have to implement the `longestConsecutive` function that takes an integer array as input and returns the length of the longest sequence of consecutive integers. + +

Problem statement for the longestConsecutive

+ +For example, in array `[4, 2, 7, 8, 1, 5, 6, 0]` we have two sequences of consecutive integers: `[0, 1, 2]` and `[4, 5, 6, 7, 8]`. The longest sequence (`[4, 5, 6, 7, 8]`) has length 5. + +# Brute Force Solution +It would be easier to find consecutive sequences if the input array is sorted. + +

Brute-force solution for the longestConsecutive

+ +Once we have the sorted array we can iterate over it and find the longest sequence. + +## Psuedo-code for the Brute Force Solution +```text +sortedInputArray = sort(inputArray) + +longest_sequence_length = 0 +sequence_length = 1 +loop index in from 1 to len(sortedInputArray) + if sortedInputArray[index] - sortedInputArray[index-1]==1: + sequence_length += 1 + else if sortedInputArray[index]==sortedInputArray[index-1]: + pass + else + sequence_length = 1 + + longest_sequence_length = max(longest_sequence_length, sequence_length) +``` + +## Time Complexity Analysis +### Best Case Scenario +For the best-case input, the brute-force solution will return the result in $O(n) + O(n \log(n))$ time. Since the time complexity of the best sorting algorithm will be $O(n \log(n))$ and the time complexity of iterating over the array is $O(n)$. We can simplify the total time complexity of the brute-force solution to $O(n \log(n))$. + +### Worst Case Scenario +In the worst-case scenario, the time complexity of the brute-force solution will be the same i.e. $O(n \log(n))$. + +## Space Complexity Analysis +We are assuming that the sorting operation is done in place for the elements in the input array. Thus, the space complexity of brute-force solution is constant i.e. $O(1)$. + +## Code for Brute Force Solution +```Go +package main + +import ( + "fmt" + "sort" + "math" +) + +func longestConsecutive(nums []int)(int){ + + // For an empty input array the length of + // longest consecutive sequence will be 0 + if len(nums)==0{ + return 0 + } + + // The best sorting algorithm will sort in + // O(nlog(n)) time + sort.Ints(nums) + + // This variable will contain the length + // of longest consecutive sequence + longestSequenceLength := 1 + + // Temporary variable to store the length + // of the current sequence + sequenceLength := 1 + + for index:=1;indexOptimized solution for the longestConsecutive

+ +If the `value` is the first element in a consecutive sequence, it implies that `value-1` does not exist in the `inputArray`. So we can iterate over all the elements in `inputArray` and identify the first elements of consecutive sequences by searching for `inputArray[index]-1` in the hashmap. + +

Optimized solution for the longestConsecutive

+ +Once we have found the first element of consecutive sequence we can keep looking for the next value in the hashmap until the sequence is broken. + +

Optimized solution for the longestConsecutive

+ +## Psuedo code for the Optimized Solution +```text +hashmap = HashMap() +loop value in inputArray + if not hashmap[value] + hashmap[value] = 1 + +longest_sequence = 0 +sequence = 0 +loop index in inputArray + value = inputArray[index] + if not hashmap[value-1] + while hashmap[value+1] + sequence += 1 + value+=1 + else + sequence = 1 + longest_sequence = max(sequence, longest_sequence) +``` + +## Time Complexity Analysis +### Best Case Scenario +The loop executed to fill the hashmap has a fixed time complexity of $O(n)$. + +If the input for the optimized solution contains only the sequences of length `1` then the nested `while` loop will not be executed. Thus, the total time complexity of the optimized solution in the best-case scenario will be $O(n) + O(n)$ or simply $O(n)$. + +### Worst Case Scenario +The check for `hashmap[value-1]` ensures that we are only looking for consecutive numbers upon encountering the first value. Thus, the total complexity of the worst-case scenario is also $O(n)$. + +## Space Complexity Analysis +The space complexity of the optimized solution is worse than the brute-force solution because it takes extra $O(n)$ space to store the hashmap. + +## Code for Optimized Solution +```Go +package main + +import ( + "fmt" + "math" +) + +func longestConsecutive(nums []int)(int){ + + // Return 0 for the empty nums array + if len(nums)==0{ + return 0 + } + + // Create a hashmap of all values in the nums array + hashmap := make(map[int]int) + for index:=0;index + +Thank you for taking the time to read this blog post! If you found this content valuable and would like to stay updated with my latest posts consider subscribing to my RSS Feed. + +# Resources +128. Longest Consecutive Sequence +Leetcode 128 - LONGEST CONSECUTIVE SEQUENCE diff --git a/content/posts/dsa/longest-consecutive/longest-consecutive-brute-force.png b/content/posts/dsa/longest-consecutive/longest-consecutive-brute-force.png new file mode 100644 index 0000000..bd811bf Binary files /dev/null and b/content/posts/dsa/longest-consecutive/longest-consecutive-brute-force.png differ diff --git a/content/posts/dsa/longest-consecutive/longest-consecutive-cover.png b/content/posts/dsa/longest-consecutive/longest-consecutive-cover.png new file mode 100644 index 0000000..faa4ae7 Binary files /dev/null and b/content/posts/dsa/longest-consecutive/longest-consecutive-cover.png differ diff --git a/content/posts/dsa/longest-consecutive/longest-consecutive-optimized1.png b/content/posts/dsa/longest-consecutive/longest-consecutive-optimized1.png new file mode 100644 index 0000000..19aa498 Binary files /dev/null and b/content/posts/dsa/longest-consecutive/longest-consecutive-optimized1.png differ diff --git a/content/posts/dsa/longest-consecutive/longest-consecutive-optimized2.png b/content/posts/dsa/longest-consecutive/longest-consecutive-optimized2.png new file mode 100644 index 0000000..8cc5471 Binary files /dev/null and b/content/posts/dsa/longest-consecutive/longest-consecutive-optimized2.png differ diff --git a/content/posts/dsa/longest-consecutive/longest-consecutive-optimized3.png b/content/posts/dsa/longest-consecutive/longest-consecutive-optimized3.png new file mode 100644 index 0000000..a4d8bb3 Binary files /dev/null and b/content/posts/dsa/longest-consecutive/longest-consecutive-optimized3.png differ diff --git a/content/posts/dsa/longest-consecutive/longest-consecutive-problem.png b/content/posts/dsa/longest-consecutive/longest-consecutive-problem.png new file mode 100644 index 0000000..921ab0f Binary files /dev/null and b/content/posts/dsa/longest-consecutive/longest-consecutive-problem.png differ