Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Getting TEL for below code. What's wrong with my code?
import java.util.*;
public class FindAllAnagramsInAString_438{
public static void main(String[] args){
String s="abab";
String p="ab";
// String s="cbaebabacd";
// String p="abc";
System.out.println(findAnagrams(s,p));
}
public static List<Integer> findAnagrams(String s, String p) {
int i=0;
int j=p.length();
List<Integer> list=new ArrayList<>();
while(j<=s.length()){
//System.out.println("Substring >>"+s.substring(i,j));
if(isAnamgram(s.substring(i,j),p)){
list.add(i);
}
i++;
j++;
}
return list;
}
public static boolean isAnamgram(String s,String p){
HashMap<Character,Integer> map=new HashMap<>();
if(s.length()!=p.length()) return false;
for(int i=0;i<s.length();i++){
char chs=s.charAt(i);
char chp=p.charAt(i);
map.put(chs,map.getOrDefault(chs,0)+1);
map.put(chp,map.getOrDefault(chp,0)-1);
}
for(int val:map.values()){
if(val!=0) return false;
}
return true;
}
}
You shouldn't be creating a whole new frequency table for each substring. Given a table for index i, the table for index i+1 changes by only 2 counts. Just modify the previous table to get the next one. Also don't bother counting characters that don't appear in the search string.
Also, don't do the whole table comparison -- just keep track of the number of mismatched counts. Again this changes by at most 2 counts per index.
Finally, don't allocate a new substring for each index.
Looks good now
HashMap<Character,Integer> pMap=new HashMap<>();
HashMap<Character,Integer> sMap=new HashMap<>();
List<Integer> list=new ArrayList<>();
for(int i=0;i<p.length();i++){
char ch=p.charAt(i);
pMap.put(ch,pMap.getOrDefault(ch,0)+1);
}
int j=0;
while(j<p.length()){
char ch=s.charAt(j);
sMap.put(ch,sMap.getOrDefault(ch,0)+1);
j++;
}
int i=0;
while(j<s.length()){
if(pMap.equals(sMap)){
list.add(i);
}
sMap.put(s.charAt(j),sMap.getOrDefault(s.charAt(j),0)+1);
if((sMap.getOrDefault(s.charAt(i),0)-1)==0){
sMap.remove(s.charAt(i));
}else{
sMap.put(s.charAt(i),sMap.getOrDefault(s.charAt(i),0)-1);
}
i++;
j++;
}
return list;
Related
The link to the problem is Q4 Traveling is Fun.
I can only think of a brute force approach to compute every possible gcd and run bfs from source to destination to check if there exists a path or not.
But the above approach gives TLE in 5 test cases.
Can anyone provide a more efficient approach ?
This is a quick implementation of the graph structure I would use:
class GCDGraph {
private Map<Integer, Set<Integer>> adj = new HashMap<>();
public GCDGraph(int g, int[] srcCities, int[] dstCities){
int n = srcCities.length;
for(int i=0;i<n;i++){
adj.put(i, new HashSet<>());
}
for(int i=0;i<n;i++){
for(int j=0;j<i;j++){
int gtmp = gcd(srcCities[i], dstCities[j]);
if(gtmp > g){
adj.get(i).add(j);
adj.get(j).add(i);
}
}
// we could add the connection i -> i (assuming srcCities[i] > g)
// but that would not help us find a path, as it introduces a cycle
}
}
private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
public Set<Integer> adjacentVertices(int vertex){ return adj.get(vertex); }
public int size(){ return adj.size(); }
public boolean isEmpty(){ return size() == 0; }
public boolean hasPath(int src, int dst){
return buildPath(src, dst, new HashSet<>());
}
private boolean buildPath(int src, int dst, Set<Integer> tmp){
if(src == dst){
return true;
} else {
for(int nextVertex : adjacentVertices(src)){
if(tmp.contains(nextVertex))
continue;
tmp.add(nextVertex);
if(buildPath(nextVertex, dst, tmp))
return true;
tmp.remove(nextVertex);
}
}
return false;
}
}
It explicitly stores the adjacency as a Map (allowing fast lookup).
It has some utility methods (size, isEmpty).
It only looks up the GCD when it is being built, and only once for each x/y pair.
And it uses recursion to perform BFS, quitting as soon as possible.
How can I calculate the time and space complexity of a program(pseudo code) as follows:
function(){
if(!areAllArrayElementsZero()){
if(hasAnyOdd()){
decreaseOneFromFirstOddElementInArray()
} else {
divideAllArrayElementByTwo()
}
}
}
Here areAllArrayElementsZero(),hasAnyOdd(),divideAllArrayElementByTwo() has the complexity O(n). Any leads would help. Actually I was designing the solution to this problem.
Here is the Java equivalent of the above pseudo code, I've designed:
package competitive;
/*
* Problem: http://www.geeksforgeeks.org/count-minimum-steps-get-given-desired-array/
*/
class formarray{
private static int[] elem;
private static boolean areAllZeros(){
for(int i=0; i<elem.length;i++){
if(elem[i]>0){
return false;
}
}
return true;
}
private static boolean hasAnyOdd(){
for(int i=0; i<elem.length;i++){
if(elem[i]%2 != 0){
// odd element discovered
return true;
}
}
return false;
}
private static boolean decreaseFirstOddByOne(){
for(int i=0; i<elem.length;i++){
if(elem[i]%2 != 0) {
// odd element discovered
elem[i]-=1;
// return true if one is decreased from first odd element
return true;
}
}
return false;
}
private static void DivideArrayElementsByTwo(){
for(int i=0; i<elem.length;i++){
// we are not checking element to be even as it has already been checked
elem[i] = elem[i]/2;
}
}
public static void main(String args[]){
elem = new int[args.length];
// assign values
for(int i=0;i<args.length;i++){
elem[i] = Integer.parseInt(args[i]);
}
int steps=0;
while(!areAllZeros()){
if(hasAnyOdd()){
// the array has odd members
if(decreaseFirstOddByOne()){
steps++;
}
} else {
DivideArrayElementsByTwo();
steps++;
}
}
System.out.println("Total steps required: "+steps);
}
}
There are exactly 4 paths of execution; sum up the cost of each, take the largest.
Or realize there are no loops and each path has a finite number of O(n) elements, making the whole thing O(n).
I tried to solve the classical knapsap problem myself. But I am getting a wrong answer as 108. Could you help me to figure out what I have done wrong. Here I am using recursion.
Weight limit is 10
answer is 5+3+2 ==> 25+15+14=54
public class KnapSack {
public static int[] weight={6,5,4,3,2};
public static int[] value={12,25,24,15,14};
public static void main(String[] args) {
System.out.println(c(0,0,10));
}
public static int c(int currentElement,int currentValue,int currentReamainder){
int p = 0;
if(currentReamainder<=0) return currentValue;
for(int i=currentElement;i<weight.length;i++){
if(currentReamainder<weight[i]) return currentValue;
p = Math.max(value[i]+c(i+1,currentValue+value[i],currentReamainder-weight[i]),c(i+1,currentValue,currentReamainder))
}
return p;
}
}
Update:
What should I do to print the weights of the optimum solution ?
Your error is this line
p=Math.max(value[i]+c(i+1,currentValue+value[i],currentReamainder-weight[i]),c(i+1,currentValue,currentReamainder));
it should be
int val = Math.max(value[i]+c(i+1,currentValue+value[i],currentReamainder-weight[i]),c(i+1,currentValue,currentReamainder));
p = Math.max(val, p);
The last bug is when you both updating currentValue and return p at the same time, so imagine the last call, when the function return currentValue, plus the last value[i] in each step, so your result is double
So , your function should be (notice I have removed the currentValue parameter, which is not necessary):
public static int c(int currentElement,int currentReamainder){
int p = 0;
if(currentReamainder<=0) return 0;
for(int i=currentElement;i<weight.length;i++){
if(currentReamainder<weight[i]) break;//This line is not valid, only when the weight array is sorted(ascending order)
int val = Math.max(value[i]+c(i+1,currentReamainder-weight[i]),c(i+1,currentReamainder));
p = Math.max(val, p);
}
return p;
}
I need to emit a 2D double array as key and value from mapper. There are questions posted in Stack Overflow, but they are not answered.
I am doing some of the matrix multiplication in a given dataset, and after that I need to emit the value of A*Atrns which will be a matrix as key and Atrans*D which will also be a matrix as value. So how to emit these matrices from mapper. And the value should be corresponding to the key itself.
ie key -----> A*Atrans--------->after multiplication the result will be a 2D array which is declared as double (matrix) lets say the result be Matrix "Ekey"(double[][] Ekey)
value ------> Atrans*D ---------> after multiplication the result will be Matrix "Eval" (double[][] Eval).
After that I need to emit these matrix to reducer for further calculations.
So in mapper:
context.write(Ekey,Eval);
Reducer:
I need to do further calculations with these Ekey and Eval.
I wrote my class:
UPDATE
public class MatrixWritable implements WritableComparable<MatrixWritable>{
/**
* #param args
*/
private double[][] value;
private double[][] values;
public MatrixWritable() {
// TODO Auto-generated constructor stub
setValue(new double[0][0]);
}
public MatrixWritable(double[][] value) {
// TODO Auto-generated constructor stub
this.value = value;
}
public void setValue(double[][] value) {
this.value = value;
}
public double[][] getValue() {
return values;
}
#Override
public void write(DataOutput out) throws IOException {
out.writeInt(value.length); // write values
for (int i = 0; i < value.length; i++) {
out.writeInt(value[i].length);
}
for (int i = 0; i < value.length; i++) {
for (int j = 0; j < value[i].length; j++) {
out.writeDouble(value[i][j]);
}
}
}
#Override
public void readFields(DataInput in) throws IOException {
value = new double[in.readInt()][];
for (int i = 0; i < value.length; i++) {
value[i] = new double[in.readInt()];
}
values = new double[value.length][value[0].length];
for(int i=0;i<value.length ; i++){
for(int j= 0 ; j< value[0].length;j++){
values[i][j] = in.readDouble();
}
}
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(value);
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MatrixWritable)) {
return false;
}
MatrixWritable other = (MatrixWritable) obj;
if (!Arrays.deepEquals(value, other.value)) {
return false;
}
return true;
}
#Override
public int compareTo(MatrixWritable o) {
// TODO Auto-generated method stub
return 0;
}
public String toString() { String separator = "|";
StringBuffer result = new StringBuffer();
// iterate over the first dimension
for (int i = 0; i < values.length; i++) {
// iterate over the second dimension
for(int j = 0; j < values[i].length; j++){
result.append(values[i][j]);
result.append(separator);
}
// remove the last separator
result.setLength(result.length() - separator.length());
// add a line break.
result.append(",");
}
return result.toString();
}
}
I am able to emit a value as matrix from mapper
context.write(...,new MatrixWritable(AAtrans));
How to emit matrix AtransD as key from mapper?
For that I need to write compareto() method, right?
What should be included in that method?
First, to implement a custom key you must implement WritableComparable. To implement a custom value you must implement Writable. In many cases since it is handy to be able to swap keys and values most people write all custom types as WritableComparable.
Here is a link to the section of Hadoop: The Definitive Guide that covers writing a WritableComparable. Writing A Custom Writable
The trick with writing out an array is that on the read side you need to know how many elements to read. So the basic patter is...
On write:
write the number of elements
write each element
On read:
read the number of elements (n)
create an array of the appropriate size
read 0 - (n-1) elements and populate array
Update
You should instantiate your array as empty in the default constructor to prevent a NullPointerException later.
The problem with your implementation is that it assumes that each inner array is of the same length. If that is true, you don't need to calculate the column length more than once. If false, you need to write the length of each row before writing the values of the row.
I would suggest something like this:
context.write(row); // as calculated above
for (int i=0; i<row; i++){
double[] rowVals = array[row];
context.write(rowVals.length);
for (int j=0; j<rowVals.length; j++)
context.write(rowVals[j]);
}
This is my first time posting question, do pardon me if anything I do is wrong.
My question here is how to get a faster algorithm from this code? i'm currently using 2 stacks to implement the code such that it will get the minimum value out of the range of index User asks for input.
Example (2,3,4,5,1), if (user selects (1,4)), it means they are looking at (2,3,4,5), which the output is 2.
Thanks.
import java.util.*;
interface StackADT <Integer> {
// check whether stack is empty
public boolean empty();
// retrieve topmost item on stack
public int peek() throws EmptyStackException;
// remove and return topmost item on stack
public int pop() throws EmptyStackException;
// insert item onto stack
public void push(int item);
}
class StackArr <Integer> implements StackADT <Integer> {
private int[] arr;
private int top;
private int maxSize;
private final int INITSIZE = 1000;
public StackArr() {
arr = (int[]) new int[INITSIZE]; // creating array of type E
top = -1; // empty stack - thus, top is not on an valid array element
maxSize = INITSIZE;
}
public boolean empty() {
return (top < 0);
}
public int peek() throws EmptyStackException {
if (!empty()) return arr[top];
else throw new EmptyStackException();
}
public int pop() throws EmptyStackException {
int obj = peek();
top--;
return obj;
}
public void push(int obj) {
if (top >= maxSize - 1) enlargeArr();
top++;
arr[top] = obj;
}
}
class RMQ{
//declare stack object
Stack<Integer> stack1;
public RMQ(){
stack1 = new Stack<Integer>();
}
public void insertInt(int num){
stack1.push(num);
}
public int findIndex(int c, int d){
Stack<Integer> tempStack = new Stack<Integer>();
Stack<Integer> popStack = new Stack<Integer>();
tempStack = (Stack)stack1.clone();
while (d != tempStack.size())
{
tempStack.pop();
}
int minValue = tempStack.pop();
popStack.push(minValue);
while (c <= tempStack.size())
{
int tempValue = tempStack.pop();
if(tempValue >= minValue)
{
continue;
}
else
{
popStack.push(tempValue);
minValue = tempValue;
}
}
return popStack.pop();
}
}
public class Pseudo{
public static void main(String[] args){
//declare variables
int inputNum;
int numOfOperations;
//create object
RMQ rmq = new RMQ();
Scanner sc = new Scanner(System.in);
//read input
inputNum = sc.nextInt();
//add integers into stack
for(int i=0; i < inputNum; i++){
rmq.insertInt(sc.nextInt());
}
// read input for number of queries
numOfOperations = sc.nextInt();
// Output queries
for(int k=0; k < numOfOperations; k++){
int output = rmq.findIndex(sc.nextInt(), sc.nextInt());
System.out.println(output);
}
}
}
Why are you using a stack? Simply use an array:
int[] myArray = new int[inputNum];
// fill the array...
// get the minimum between "from" and "to"
int minimum = Integer.MAX_VALUE;
for(int i = from ; i <= to ; ++i) {
minimum = Math.min(minimum, myArray[i])
}
And that's it!
The way I understand your question is that you want to do some preprocessing on a fixed array that then makes your find min operation of a range of elements very fast.
This answer describes an approach that does O(nlogn) preprocessing work, followed by O(1) work for each query.
Preprocessing O(nlogn)
The idea is to prepare a 2d array SMALL[a,k] where SMALL[a,k] is the minimum of the 2^k elements starting at a
You can compute this array in a recursive way by starting at k==0 and then building up the value for each higher element by combining two previous elements together.
SMALL[a,k] = min(SMALL[a,k-1] , SMALL[a+2^(k-1),k-1])
Lookup O(1) per query
You are then able to instantly find the min for any range by combining 2 preprepared answers.
Suppose you want to find the min for elements from 100 to 133. You already know the min of 32 elements 100 to 131 (in BIG[100,5]) and also the min of 32 elements from 102 to 133 (in BIG[102,5]) so you can find the smallest of these to get the answer.
This is Range Minimum Query problem.
There are some algorthms and data structures to solve it effectively