LeetCode Top Interview Questions — Easy Collection (Arrays)

Just like any other skills, the coding interview is one area where you can greatly improve with deliberate practice. So here’s what I started off with. I have solved five problems on arrays and have given out my code and output. There are more ways of solving these problems. This is how I solved mine.

1) Remove Duplicates from Sorted Array

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements?

Java Code to remove duplicates

Input: nums = [1,1,2]

Output: Array size after removing duplicates is 2

2) Best Time to Buy and Sell Stock II

Say you have an array prices for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Java Code to find the maximum profit

Input: [1,2,3,4,5]

Output: Maximum Profit is 4

3) Rotate Array

Given an array, rotate the array to the right by k steps, where k is non-negative.

Java Code to rotate an array

Input: nums = [1,2,3,4,5,6,7], k = 3

Output: [5,6,7,1,2,3,4]

4) Contains Duplicate

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Java Code to check duplicate in an array

Input: [1,2,3,1]

Output: true

5) Single Number

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

Input: nums = [4,1,2,1,2]

Output: 4

So these were my solutions. I hope to come up with more from LeetCode. Hope to see you get motivated as I feel right now!

If you want to have a look at my GitHub account, go visit https://github.com/minu27

And here’s my LinkedIn page https://www.linkedin.com/in/minalvaity/ to connect with me.

Contact me on my email minal.vaity95@gmail.com

Software Developer in Chicago