Skip to content

Instantly share code, notes, and snippets.

@yeshvantbhavnasi
Last active September 10, 2019 04:34
Show Gist options
  • Save yeshvantbhavnasi/d03813f2b11de11b928ac4eeb273b628 to your computer and use it in GitHub Desktop.
Save yeshvantbhavnasi/d03813f2b11de11b928ac4eeb273b628 to your computer and use it in GitHub Desktop.
Day1: Leetcode challenge problem solutions
class Solution162 {
/**
* https://leetcode.com/problems/find-peak-element/
*/
public int findPeakElement(int[] nums) {
return search(nums, 0, nums.length - 1);
}
public int search(int[] nums, int l, int r) {
if (l == r)
return l;
int mid = (l + r) / 2;
if (nums[mid] > nums[mid + 1])
return search(nums, l, mid);
return search(nums, mid + 1, r);
}
}
class Solution448 {
//448. Find All Numbers Disappeared in an Array
/**
* https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
* Time complexity: O(n) = 2*n
* Space complexity: O(1) constant space just additional space to return the unvisited elements
*/
public List<Integer> findDisappearedNumbers(int[] nums) {
int n = nums.length+1; //as the array elements are from 1 to n so to indicate add pading greater than n.
//indicate the elements visited by adding n to each visited element
for (int i: nums) {
int reali = i % n;
nums[reali-1] += n;
}
List<Integer> rlist = new ArrayList<>();
//now iterate the elements to find any number less than n to indicate we didnt visited
for (int i=0; i< n-1;i++) {
if(nums[i] < n) {
rlist.add(i+1);
}
}
return rlist;
}
}
class Solution996 {
Set<String> words_perfect;
Map<String, String> words_cap;
Map<String, String> words_vow;
public String[] spellchecker(String[] wordlist, String[] queries) {
words_perfect = new HashSet();
words_cap = new HashMap();
words_vow = new HashMap();
for (String word: wordlist) {
words_perfect.add(word);
String wordlow = word.toLowerCase();
words_cap.putIfAbsent(wordlow, word);
String wordlowDV = devowel(wordlow);
words_vow.putIfAbsent(wordlowDV, word);
}
String[] ans = new String[queries.length];
int t = 0;
for (String query: queries)
ans[t++] = solve(query);
return ans;
}
public String solve(String query) {
if (words_perfect.contains(query))
return query;
String queryL = query.toLowerCase();
if (words_cap.containsKey(queryL))
return words_cap.get(queryL);
String queryLV = devowel(queryL);
if (words_vow.containsKey(queryLV))
return words_vow.get(queryLV);
return "";
}
public String devowel(String word) {
StringBuilder ans = new StringBuilder();
for (char c: word.toCharArray())
ans.append(isVowel(c) ? '*' : c);
return ans.toString();
}
public boolean isVowel(char c) {
return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment