Syntax highlighter header

Tuesday, 28 April 2020

Number of ways to insert two pairs of parentheses into a string of N characters

I came across an interesting codding problem at https://www.geeksforgeeks.org/number-of-ways-to-insert-two-pairs-of-parentheses-into-a-string-of-n-characters/

Problem:
Given a string str of length N, the task is to find the number of ways to insert only 2 pairs of parentheses into the given string such that the resultant string is still valid.
Example:
Input: str = “ab”Output: 6((a))b, ((a)b), ((ab)), (a)(b), (a(b)), a((b))which are a total of 6 ways.
Solution:
Approach: it can be observed that for the lengths of the string 1, 2, 3, …, N a series will be formed as 1, 6, 20, 50, 105, 196, 336, 540, … whose Nth term is (N + 1)2 * ((N + 1)2 – 1) / 12. 
The solution is good but the page does not provide derivation of the formula which is base of the solution.  I tried to derive the formula on my own and this is what I came up with:

  1. There are N+1 places where parenthesis can be placed. One in the beginning, N-1 in middle and one at end. So there are   ((N + 1)4 )/4 ways to place the parenthesis. We can place multiple parenthesis at same location, one opening parenthesis can be replaced with another opening parenthesis and closing parenthesis can be replaced with other closing parenthesis therefore we divided by 4.
  2. Some of the combinations counted in previous step are invalid so we need to subtract them. 
  3. All four parenthesis at same location is not a valid case there are (N+1)/4  such combinations so we need to subtract them.
  4. Three parenthesis being at one location and one being at one location is also not a valid combination. There are (N+1)*N/4 such combinations so we need to subtract them.
  5. After the above considerations We come up with (N + 1)2 * ((N + 1)2 – 1) / 4 ways.
  6. Now if you think closely out of following 6 possible combinations of parenthesis only first two are valid. You ignore string character in between parenthesis.
    1. (())
    2. ()()
    3. )()(
    4. )(()
    5. ))((
    6. ())(
  7. So we need to divide by 3 to get valid ways of putting parenthesis. So we get the final formula as (N + 1)2 * ((N + 1)2 – 1) / 12.

            Thursday, 16 April 2020

            An interesting Google interview question

            Recently I read about an interesting Google interview question at https://www.geeksforgeeks.org/count-strings-can-formed-using-b-c-given-constraints/

            The problem statement is:
            Given a length n, count the number of strings of length n that can be made using ‘a’, ‘b’ and ‘c’ with at-most one ‘b’ and two ‘c’s allowed.
            The page on GeeksForGeeks provide two programmatic solutions using recursion. But most interesting   one is mathematical one which directly calculate value. It took me quite long time to derive that formula. The formula is:
            count = 1 + 2n+ n*((n*n)-1)/2 
            Here I want to provide derivation for this formula. You may find it useful.


            1. count of strings with no b's and no c's = 1
            2. count of strings with one b and no c's = n
            3. count of strings with no b's and one c = n
            4. count of strings with one b and one c = n*(n-1)
            5. count of strings with one b and two c's = n*(n-1)*(n-2)/2;
            6. count of strings with no b and two c's = n*(n-1)/2


            If you add all 6 values then you will get
            count = 1 + 2n+ n*((n*n)-1)/2
            The above formula works only for n greater than or equal to 3. 

            Tuesday, 14 April 2020

            The ACL permission error while exporting Cloud Watch logs to S3

            Yesterday I struggled for more than 6 hours to export Cloud Watch logs to S3 bucket. I was getting the following error:
            The ACL permission for the selected bucket is not correct. The Amazon S3 bucket must reside in the same region as the log data that you want to export. Learn more.


            I tried following all the steps mentioned in the link but still it did not work. Later on I found the mistake, it interesting one so I am writing it in my blog so that you don't make same mistake.

            says that you need to set following policy to S3 bucket:
            
            {
                "Version": "2012-10-17",
                "Statement": [
                  {
                      "Action": "s3:GetBucketAcl",
                      "Effect": "Allow",
                      "Resource": "arn:aws:s3:::my-exported-logs",
                      "Principal": { "Service": "logs.us-west-2.amazonaws.com" }
                  },
                  {
                      "Action": "s3:PutObject" ,
                      "Effect": "Allow",
                      "Resource": "arn:aws:s3:::my-exported-logs/random-string/*",
                      "Condition": { "StringEquals": { "s3:x-amz-acl": "bucket-owner-full-control" } },
                      "Principal": { "Service": "logs.us-west-2.amazonaws.com" }
                  }
                ]
            }
            
            
            Here my-exported-logs is the bucket name and it needs to be replaced with your bucket name and us-west-2 needs to be replaced with your region code for Mumbai it is ap-south-1. 

            The page says that random-string can be replaced with any random string which makes you believe that this string is not important but that is wrong. It is most important string for exporting logs to S3. The random string which you use in bucket permission needs to be provide as S3 bucket prefix while exporting logs to S3 bucket. If you don't provide S3 bucket prefix or provide a different prefix then you get the ACL error because the policy provide s3:PutObject permission only on random-string directory so if we try to put logs in some other directory then it will fail. The following export configuration works.
            The only difference between working and not working dialog box is random-string being provided as S3 bucket prefix. I learned it the hard way by wasting 6 hours.

            Wednesday, 5 February 2020

            Kubernetes Error: Error response from daemon: invalid mode

            Recently I was trying to mount a persistence volume in a Kubernetes pod. I faced the error "Error: Error response from daemon: invalid mode". After struggling for a long time and searching internet I was able to solve this problem. Here I am writing the solution to this problem. I was trying to follow tutorial https://kubernetes.io/docs/tasks/configure-pod-container/configure-persistent-volume-storage/ . Only difference  being that I was trying it on windows rather than Linux.

            I tried with following persistance_volume.yaml file
             
            apiVersion: v1
            kind: PersistentVolume
            metadata:
              name: task-pv-volume
              labels:
                type: local
            spec:
              storageClassName: manual
              capacity:
                storage: 10Gi
              accessModes:
                - ReadWriteOnce
              hostPath:
                path: "c:/jasvant/kubernetes/persistence_volume/data"
            
            
            My directory on windows was present at "C:\jasvant\kubernetes\persistence_volume\data" so I replaced all '\' with '/'. But is did not work and pod container failed to start.
            
            C:\Users\jasvant\kubernetes>kubectl get pod
            NAME                                  READY   STATUS                 RESTARTS   AGE
            hello-minikube-6fb6cb79cc-8drt9       1/1     Running                6          130d
            kubernetes-bootcamp-dd569fc9c-bt74m   1/1     Running                5          96d
            kubernetes-bootcamp-dd569fc9c-fl64v   1/1     Running                5          96d
            task-pv-pod                           0/1     CreateContainerError   0          62s
            
            

            The container failed to start with CreateContainerError. When I described the pod I got the following error:
            
            C:\Users\jasvant\kubernetes>kubectl describe pod  task-pv-pod
            Name:         task-pv-pod
            Namespace:    default
            Priority:     0
            Node:         minikube/10.0.2.15
            Start Time:   Wed, 05 Feb 2020 14:27:59 +0530
            Labels:       
            Annotations:  
            Status:       Pending
            IP:           172.17.0.7
            Containers:
              task-pv-container:
                Container ID:
                Image:          nginx
                Image ID:
                Port:           80/TCP
                Host Port:      0/TCP
                State:          Waiting
                  Reason:       CreateContainerError
                Ready:          False
                Restart Count:  0
                Environment:    
                Mounts:
                  /usr/share/nginx/html from task-pv-storage (rw)
                  /var/run/secrets/kubernetes.io/serviceaccount from default-token-scccw (ro)
            Conditions:
              Type              Status
              Initialized       True
              Ready             False
              ContainersReady   False
              PodScheduled      True
            Volumes:
              task-pv-storage:
                Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
                ClaimName:  task-pv-claim
                ReadOnly:   false
              default-token-scccw:
                Type:        Secret (a volume populated by a Secret)
                SecretName:  default-token-scccw
                Optional:    false
            QoS Class:       BestEffort
            Node-Selectors:  
            Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                             node.kubernetes.io/unreachable:NoExecute for 300s
            Events:
              Type     Reason     Age                 From               Message
              ----     ------     ----                ----               -------
              Normal   Scheduled  2m14s               default-scheduler  Successfully assigned default/task-pv-pod to minikube
              Normal   Pulled     14s (x8 over 2m8s)  kubelet, minikube  Successfully pulled image "nginx"
              Warning  Failed     14s (x8 over 2m8s)  kubelet, minikube  Error: Error response from daemon: invalid mode: /usr/share/nginx/html
              Normal   Pulling    4s (x9 over 2m13s)  kubelet, minikube  Pulling image "nginx"
            
            

            This error message fails to give any hint to actual problem. The root cause is that HostPath.path need to be a path on VM created by Minikube and not a directory path on windows machine. so C: was not accepted by minikube. It is not impossible to mount a windows directory onto VM and use that directory as persistence volume storage directory. By default 'C:\Users' directory from Windows machine is mounted at   /c/Users folder in VM. So "/c/Users/jasvant/kubernetes/persistence_volume/data" will work for me. But if you create any directory out of  'C:\Users' directory then it will not work.. Please refer to https://minikube.sigs.k8s.io/docs/tasks/mount/ for more information.

            If you want to login into VM created by Minikube for running Kubernetes cluster. you can use "minikube ssh" command on your windows machine. It will open a ssh to VM and you can browse the file system there.




            Monday, 9 September 2019

            java.util.ConcurrentModificationException: KafkaConsumer is not safe for multi-threaded access

            I got the following error while trying to run spark streaming code for one of my assignment.
            
            java.util.ConcurrentModificationException: KafkaConsumer is not safe for multi-threaded access
            
            
            When I searched the internet I found that it is a bug and it is fixed in latest version. The link to bug is: https://jira.apache.org/jira/browse/SPARK-19185
            It is fixed in version 2.4.0 

            I used the following pom.xml file to fix this problem.