Determine if a string has all unique characters
Problem Implement an algorithm to determine if a string has all the characters…
September 03, 2020
Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Example
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
We can keep a index variable which will keep a tab on all non-zero values.
On iteration, we can move each non-zero value to left side.
public void moveZeroes_simple(int[] nums) {
int left=0;
for (int i=0; i<nums.length; i++) {
if (nums[i] != 0) {
nums[left] = nums[i];
left ++;
}
}
//copy zeroes to remaining array
for (int i=left; i<nums.length; i++) {
nums[i] = 0;
}
}
Its O(n)
We can do a slight modification to above solution. The point where we just move non-zero value to left. We can do a swap as well.
public void moveZeroes(int[] nums) {
int left=0;
for (int i=0; i<nums.length; i++) {
if (nums[i] != 0) {
//swap
int t = nums[i];
nums[i] = nums[left];
nums[left] = t;
left ++;
}
}
}
Its O(n)
But, its better since we are not using another loop to copy zero.
Problem Implement an algorithm to determine if a string has all the characters…
Problem Statement Given a linked list, swap every two adjacent nodes and return…
Problem Statement Given a Binary tree, print out nodes in level order traversal…
This is kind of preliminary technique of sorting. And, this is the first…
Problem Statement Given a linked list, remove the n-th node from the end of list…
Problem Statement You are given a rows x cols matrix grid. Initially, you are…
In this post, we will see some of the frequently used concepts/vocabulary in…
System design interview is pretty common these days, specially if you are having…
Introduction You are given an array of integers with size N, and a number K…
Graph Topological Sorting This is a well known problem in graph world…
Problem Statement Given a Binary tree, print out nodes in level order traversal…
Problem Statement Given an array nums of n integers and an integer target, are…