Back to Blog
November 5, 20252 min read

Day #3/50 of Learning DSA

Linear Search, Rotate Array by One, Max Consecutive Ones

#DSA#dsawithbimlesh#General Programming

Day #3/50 of Learning DSA

Today marks the third day of my journey into learning Data Structures and Algorithms (DSA). I've tackled some intriguing problems that have deepened my understanding of fundamental concepts. I explored the Linear Search algorithm, which involves finding a target element within an array. Additionally, I delved into the problem of rotating an array by one position in a clockwise direction, a task that enhances my grasp of array manipulation. Lastly, I worked on finding the maximum number of consecutive ones in a binary array, a challenge that tests logical thinking and problem-solving skills. Despite having some urgent tasks to attend to, I'm excited to share my progress and insights from today's learning experience.

Linear Seach:

Given an array, nums[] of n integers, and an integer element target, find whether element target is present in the array. Return the index of the first occurrence of target in the array, or -1 if it doesn't exist.

Approach:

  • Run a loop to search the target element.

  • Return the index of the element if found, else return -1.

    int search(vector<int>& nums, int target) {
        for(int i=0; i<nums.size(); i++){
            if (nums[i] == target) return i;
        }
        return -1;
    }

Rotate Array by One:

Given an array nums, rotate the array by one position in clockwise direction.

Approach:

  • Store the last element of the array in temp variable.

  • Keep shifting the elements from index i to i-1 and lastly update the first element nums[0] with temp.

    void rotate(vector<int> &nums) {
        int n = nums.size();
        int temp = nums[n-1];
        for (int i=n-1; i>=0; i--){
            nums[i] = nums[i-1];
        }
        nums[0] = temp;
    }

Max Consecutive Ones:

Given a binary array nums, return the maximum number of consecutive 1's in the array.

Approach:

  • Run a loop to traverse the array and increase the counter if occurrence of 1 continue.

  • Update the maxCount if with max of count & maxCount, as count reset if 0 is encountered.

    int findMaxConsecutiveOnes(vector<int>& nums) {
        int count = 0;
        int maxCount = 0;
        for (int val: nums){
            if (val == 0){
                count = 0;
            }
            else{
                count++;
                maxCount = max(count, maxCount);
            }
        }
        return maxCount;
    }

Read Next