Problem solving in Array and String
What you will learn
Solving Arrays and String questions
Using two pointer approach
Finding missing and duplicate elements in Array / strings
Searching an element in Array / String
Description
Array is a very basic data structure representing a group of similar elements, accessed by index. Array data structure can be effectively stored inside the computer and provides fast access to the all its elements
Arrays store values of the same data type. Address of elements are stored consecutively in memory
length is fixed. inserting or deleting an element in middle is not easy
Declaration:
int[] nums = {1,2,4} //initializing with values
int[] nums = new int[10] //initializing with size. 0 will be initialized in all indexes if we declare without variables
Accessing an element:
Array index starts from 0..length-1
int[] nums = {1,2,4}
nums[0] — 1
nums[1] — 2
nums[2] — 4
Sorting an element:
Arrays.sort(nums);
Filling arary element with some values:
Arrays.fill(nums, -1) -> this will assign all values in the array as -1
Searching
When we need to seach a particular element in an array, we can do that in two ways such as
1. Linear search – We need to traverse the array completely and check if we find the element
2. Binary search — We can do binary search only when the array is sorted. Below is the command to use binary search and find if the element is present in array or not.
Arrays.binarySearch(array,value to find) -> returns index
Strings
String are enclosed inside ” “.
Below are the built in methods to use while working with Strings.
length of a string — length()
seeing character at some position — charAt()
if a string contains particular substring — contains()
Converting string to char array — toCharArray()
taking substrings — substring()
Replacing in string — replace()
Replacing first occurence — replaceFirst()
converting lower and capital letters inside string — toUpperCase() and toLowerCase()
to convert into character array – .toCharArray()
Content