Valid Palindrome - Leet Code Solution
Problem Statement Given a string, determine if it is a palindrome, considering…
September 01, 2020
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.
Example
Input: [1,2,3,1]
Output: true
Lets talk about the simplest solution first.
public boolean containsDuplicate_bruteforce(int[] nums) {
if (nums == null || nums.length == 0) return false;
int l = nums.length;
for (int i=0; i<l; i++) {
for (int j=i+1; j<l; j++) {
if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
Its O(n^2)
Another simple solution is to sort the numbers first. Then, match consecutive numbers. If you find any pair having same value, return true.
public boolean containsDuplicate(int[] nums) {
if (nums == null || nums.length == 0) return false;
Arrays.sort(nums);
int l = nums.length;
for (int i=1; i<l; i++) {
if (nums[i-1] == nums[i]) {
return true;
}
}
return false;
}
Complexity for sorting is O(nlogn)
Total complexity is also O(nlogn)
Lets utilize a HashSet. A HashSet is a data structure which contains all unique elements, and the complexity to search and adding an element is O(1)
public boolean containsDuplicate_extraMemory(int[] nums) {
if (nums == null || nums.length == 0) return false;
Set<Integer> set = new HashSet<>();
int l = nums.length;
for (int i=0; i<l; i++) {
if (set.contains(nums[i])) {
return true;
}
set.add(nums[i]);
}
return false;
}
Its O(n)
Problem Statement Given a string, determine if it is a palindrome, considering…
A number consists of digits. Example: 843. Its a 3-digit number. Radix sort…
Problem Statement Given a sorted array nums, remove the duplicates in-place such…
Problem Statement Given two arrays, write a function to compute their…
It is one of a simple algorithm to study for a beginner to understanding sorting…
Problem Statement You are given a string text of words that are placed among…
Introduction This post has the complete code to send email through smtp server…
Introduction In a normal email sending code from python, I’m getting following…
Introduction In one of my app, I was using to talk to . I have used some event…
Introduction So you have a Django project, and want to run it using docker image…
Introduction It is very important to introduce few process so that your code and…
Introduction In this post, we will see a sample Jenkin Pipeline Groovy script…