📜  门| GATE CS Mock 2018 |问题 7(1)

📅  最后修改于: 2023-12-03 14:58:22.626000             🧑  作者: Mango

GATE CS Mock 2018: Question 7

Introduction

This question is from the GATE CS Mock test conducted in 2018. It primarily focuses on data structures and algorithm concepts.

Problem Statement

Given an array of integers, the task is to find the maximum length of any subarray of consecutive integers.

Example

Input:

[2, 0, 2, 1, 4, 3, 1, 0]

Output:

Length of the longest consecutive subarray is 5
Solution

We can solve this problem using the following approach:

  1. Create an empty hash set hashSet.
  2. Traverse the given array from start to end.
  3. If the current element is not present in the hash set, add it.
  4. If the current element is present in the hash set, it means that we have encountered a consecutive subarray of integers. So, we need to calculate the length of this subarray.
  5. To calculate the length, we start from the current element and keep incrementing the integer until we don't find the next integer in the hash set.
  6. Update the maximum length found so far.
Pseudocode
function findMaxLength(arr):
    n = length of arr
    hashSet = empty set
    
    maxLength = 0
    length = 0
    
    for i from 0 to n-1:
        if arr[i] not in hashSet:
            hashSet.add(arr[i])
            length = 1
            
            j = arr[i] + 1
            while j in hashSet:
                hashSet.add(j)
                length = length + 1
                j = j + 1
            
            j = arr[i] - 1
            while j in hashSet:
                hashSet.add(j)
                length = length + 1
                j = j - 1
            
            maxLength = max(maxLength, length)
    
    return maxLength
Complexity Analysis
  • Time Complexity: O(n), where n is the length of the given array.
  • Space Complexity: O(n).
Conclusion

The problem of finding the maximum length of a subarray of consecutive integers is an interesting problem that can be solved efficiently using hash sets. It's a good exercise to practice data structure and algorithm concepts.